PageRenderTime 79ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/post.php

https://bitbucket.org/aukhanev/xdn-wordpress31
PHP | 5239 lines | 2526 code | 712 blank | 2001 comment | 723 complexity | f7be7b0a182f9e1516b54b7bc5439c00 MD5 | raw file
  1. <?php
  2. /**
  3. * Post functions and post utility function.
  4. *
  5. * @package WordPress
  6. * @subpackage Post
  7. * @since 1.5.0
  8. */
  9. //
  10. // Post Type Registration
  11. //
  12. /**
  13. * Creates the initial post types when 'init' action is fired.
  14. *
  15. * @since 2.9.0
  16. */
  17. function create_initial_post_types() {
  18. register_post_type( 'post', array(
  19. 'public' => true,
  20. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  21. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  22. 'capability_type' => 'post',
  23. 'map_meta_cap' => true,
  24. 'hierarchical' => false,
  25. 'rewrite' => false,
  26. 'query_var' => false,
  27. 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
  28. ) );
  29. register_post_type( 'page', array(
  30. 'public' => true,
  31. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  32. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  33. 'capability_type' => 'page',
  34. 'map_meta_cap' => true,
  35. 'hierarchical' => true,
  36. 'rewrite' => false,
  37. 'query_var' => false,
  38. 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
  39. ) );
  40. register_post_type( 'attachment', array(
  41. 'labels' => array(
  42. 'name' => __( 'Media' ),
  43. ),
  44. 'public' => true,
  45. 'show_ui' => false,
  46. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  47. '_edit_link' => 'media.php?attachment_id=%d', /* internal use only. don't use this when registering your own post type. */
  48. 'capability_type' => 'post',
  49. 'map_meta_cap' => true,
  50. 'hierarchical' => false,
  51. 'rewrite' => false,
  52. 'query_var' => false,
  53. 'show_in_nav_menus' => false,
  54. ) );
  55. register_post_type( 'revision', array(
  56. 'labels' => array(
  57. 'name' => __( 'Revisions' ),
  58. 'singular_name' => __( 'Revision' ),
  59. ),
  60. 'public' => false,
  61. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  62. '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
  63. 'capability_type' => 'post',
  64. 'map_meta_cap' => true,
  65. 'hierarchical' => false,
  66. 'rewrite' => false,
  67. 'query_var' => false,
  68. 'can_export' => false,
  69. ) );
  70. register_post_type( 'nav_menu_item', array(
  71. 'labels' => array(
  72. 'name' => __( 'Navigation Menu Items' ),
  73. 'singular_name' => __( 'Navigation Menu Item' ),
  74. ),
  75. 'public' => false,
  76. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  77. 'hierarchical' => false,
  78. 'rewrite' => false,
  79. 'query_var' => false,
  80. ) );
  81. register_post_status( 'publish', array(
  82. 'label' => _x( 'Published', 'post' ),
  83. 'public' => true,
  84. '_builtin' => true, /* internal use only. */
  85. 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
  86. ) );
  87. register_post_status( 'future', array(
  88. 'label' => _x( 'Scheduled', 'post' ),
  89. 'protected' => true,
  90. '_builtin' => true, /* internal use only. */
  91. 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
  92. ) );
  93. register_post_status( 'draft', array(
  94. 'label' => _x( 'Draft', 'post' ),
  95. 'protected' => true,
  96. '_builtin' => true, /* internal use only. */
  97. 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
  98. ) );
  99. register_post_status( 'pending', array(
  100. 'label' => _x( 'Pending', 'post' ),
  101. 'protected' => true,
  102. '_builtin' => true, /* internal use only. */
  103. 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
  104. ) );
  105. register_post_status( 'private', array(
  106. 'label' => _x( 'Private', 'post' ),
  107. 'private' => true,
  108. '_builtin' => true, /* internal use only. */
  109. 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
  110. ) );
  111. register_post_status( 'trash', array(
  112. 'label' => _x( 'Trash', 'post' ),
  113. 'internal' => true,
  114. '_builtin' => true, /* internal use only. */
  115. 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
  116. 'show_in_admin_status_list' => true,
  117. ) );
  118. register_post_status( 'auto-draft', array(
  119. 'label' => 'auto-draft',
  120. 'internal' => true,
  121. '_builtin' => true, /* internal use only. */
  122. ) );
  123. register_post_status( 'inherit', array(
  124. 'label' => 'inherit',
  125. 'internal' => true,
  126. '_builtin' => true, /* internal use only. */
  127. 'exclude_from_search' => false,
  128. ) );
  129. }
  130. add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
  131. /**
  132. * Retrieve attached file path based on attachment ID.
  133. *
  134. * You can optionally send it through the 'get_attached_file' filter, but by
  135. * default it will just return the file path unfiltered.
  136. *
  137. * The function works by getting the single post meta name, named
  138. * '_wp_attached_file' and returning it. This is a convenience function to
  139. * prevent looking up the meta name and provide a mechanism for sending the
  140. * attached filename through a filter.
  141. *
  142. * @since 2.0.0
  143. * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
  144. *
  145. * @param int $attachment_id Attachment ID.
  146. * @param bool $unfiltered Whether to apply filters.
  147. * @return string The file path to the attached file.
  148. */
  149. function get_attached_file( $attachment_id, $unfiltered = false ) {
  150. $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
  151. // If the file is relative, prepend upload dir
  152. if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
  153. $file = $uploads['basedir'] . "/$file";
  154. if ( $unfiltered )
  155. return $file;
  156. return apply_filters( 'get_attached_file', $file, $attachment_id );
  157. }
  158. /**
  159. * Update attachment file path based on attachment ID.
  160. *
  161. * Used to update the file path of the attachment, which uses post meta name
  162. * '_wp_attached_file' to store the path of the attachment.
  163. *
  164. * @since 2.1.0
  165. * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
  166. *
  167. * @param int $attachment_id Attachment ID
  168. * @param string $file File path for the attachment
  169. * @return bool False on failure, true on success.
  170. */
  171. function update_attached_file( $attachment_id, $file ) {
  172. if ( !get_post( $attachment_id ) )
  173. return false;
  174. $file = apply_filters( 'update_attached_file', $file, $attachment_id );
  175. $file = _wp_relative_upload_path($file);
  176. return update_post_meta( $attachment_id, '_wp_attached_file', $file );
  177. }
  178. /**
  179. * Return relative path to an uploaded file.
  180. *
  181. * The path is relative to the current upload dir.
  182. *
  183. * @since 2.9.0
  184. * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
  185. *
  186. * @param string $path Full path to the file
  187. * @return string relative path on success, unchanged path on failure.
  188. */
  189. function _wp_relative_upload_path( $path ) {
  190. $new_path = $path;
  191. if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
  192. if ( 0 === strpos($new_path, $uploads['basedir']) ) {
  193. $new_path = str_replace($uploads['basedir'], '', $new_path);
  194. $new_path = ltrim($new_path, '/');
  195. }
  196. }
  197. return apply_filters( '_wp_relative_upload_path', $new_path, $path );
  198. }
  199. /**
  200. * Retrieve all children of the post parent ID.
  201. *
  202. * Normally, without any enhancements, the children would apply to pages. In the
  203. * context of the inner workings of WordPress, pages, posts, and attachments
  204. * share the same table, so therefore the functionality could apply to any one
  205. * of them. It is then noted that while this function does not work on posts, it
  206. * does not mean that it won't work on posts. It is recommended that you know
  207. * what context you wish to retrieve the children of.
  208. *
  209. * Attachments may also be made the child of a post, so if that is an accurate
  210. * statement (which needs to be verified), it would then be possible to get
  211. * all of the attachments for a post. Attachments have since changed since
  212. * version 2.5, so this is most likely unaccurate, but serves generally as an
  213. * example of what is possible.
  214. *
  215. * The arguments listed as defaults are for this function and also of the
  216. * {@link get_posts()} function. The arguments are combined with the
  217. * get_children defaults and are then passed to the {@link get_posts()}
  218. * function, which accepts additional arguments. You can replace the defaults in
  219. * this function, listed below and the additional arguments listed in the
  220. * {@link get_posts()} function.
  221. *
  222. * The 'post_parent' is the most important argument and important attention
  223. * needs to be paid to the $args parameter. If you pass either an object or an
  224. * integer (number), then just the 'post_parent' is grabbed and everything else
  225. * is lost. If you don't specify any arguments, then it is assumed that you are
  226. * in The Loop and the post parent will be grabbed for from the current post.
  227. *
  228. * The 'post_parent' argument is the ID to get the children. The 'numberposts'
  229. * is the amount of posts to retrieve that has a default of '-1', which is
  230. * used to get all of the posts. Giving a number higher than 0 will only
  231. * retrieve that amount of posts.
  232. *
  233. * The 'post_type' and 'post_status' arguments can be used to choose what
  234. * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
  235. * post types are 'post', 'pages', and 'attachments'. The 'post_status'
  236. * argument will accept any post status within the write administration panels.
  237. *
  238. * @see get_posts() Has additional arguments that can be replaced.
  239. * @internal Claims made in the long description might be inaccurate.
  240. *
  241. * @since 2.0.0
  242. *
  243. * @param mixed $args Optional. User defined arguments for replacing the defaults.
  244. * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
  245. * @return array|bool False on failure and the type will be determined by $output parameter.
  246. */
  247. function get_children($args = '', $output = OBJECT) {
  248. $kids = array();
  249. if ( empty( $args ) ) {
  250. if ( isset( $GLOBALS['post'] ) ) {
  251. $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
  252. } else {
  253. return $kids;
  254. }
  255. } elseif ( is_object( $args ) ) {
  256. $args = array('post_parent' => (int) $args->post_parent );
  257. } elseif ( is_numeric( $args ) ) {
  258. $args = array('post_parent' => (int) $args);
  259. }
  260. $defaults = array(
  261. 'numberposts' => -1, 'post_type' => 'any',
  262. 'post_status' => 'any', 'post_parent' => 0,
  263. );
  264. $r = wp_parse_args( $args, $defaults );
  265. $children = get_posts( $r );
  266. if ( !$children )
  267. return $kids;
  268. update_post_cache($children);
  269. foreach ( $children as $key => $child )
  270. $kids[$child->ID] = $children[$key];
  271. if ( $output == OBJECT ) {
  272. return $kids;
  273. } elseif ( $output == ARRAY_A ) {
  274. foreach ( (array) $kids as $kid )
  275. $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
  276. return $weeuns;
  277. } elseif ( $output == ARRAY_N ) {
  278. foreach ( (array) $kids as $kid )
  279. $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
  280. return $babes;
  281. } else {
  282. return $kids;
  283. }
  284. }
  285. /**
  286. * Get extended entry info (<!--more-->).
  287. *
  288. * There should not be any space after the second dash and before the word
  289. * 'more'. There can be text or space(s) after the word 'more', but won't be
  290. * referenced.
  291. *
  292. * The returned array has 'main' and 'extended' keys. Main has the text before
  293. * the <code><!--more--></code>. The 'extended' key has the content after the
  294. * <code><!--more--></code> comment.
  295. *
  296. * @since 1.0.0
  297. *
  298. * @param string $post Post content.
  299. * @return array Post before ('main') and after ('extended').
  300. */
  301. function get_extended($post) {
  302. //Match the new style more links
  303. if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
  304. list($main, $extended) = explode($matches[0], $post, 2);
  305. } else {
  306. $main = $post;
  307. $extended = '';
  308. }
  309. // Strip leading and trailing whitespace
  310. $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
  311. $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
  312. return array('main' => $main, 'extended' => $extended);
  313. }
  314. /**
  315. * Retrieves post data given a post ID or post object.
  316. *
  317. * See {@link sanitize_post()} for optional $filter values. Also, the parameter
  318. * $post, must be given as a variable, since it is passed by reference.
  319. *
  320. * @since 1.5.1
  321. * @uses $wpdb
  322. * @link http://codex.wordpress.org/Function_Reference/get_post
  323. *
  324. * @param int|object $post Post ID or post object.
  325. * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
  326. * @param string $filter Optional, default is raw.
  327. * @return mixed Post data
  328. */
  329. function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
  330. global $wpdb;
  331. $null = null;
  332. if ( empty($post) ) {
  333. if ( isset($GLOBALS['post']) )
  334. $_post = & $GLOBALS['post'];
  335. else
  336. return $null;
  337. } elseif ( is_object($post) && empty($post->filter) ) {
  338. _get_post_ancestors($post);
  339. $_post = sanitize_post($post, 'raw');
  340. wp_cache_add($post->ID, $_post, 'posts');
  341. } else {
  342. if ( is_object($post) )
  343. $post_id = $post->ID;
  344. else
  345. $post_id = $post;
  346. $post_id = (int) $post_id;
  347. if ( ! $_post = wp_cache_get($post_id, 'posts') ) {
  348. $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id));
  349. if ( ! $_post )
  350. return $null;
  351. _get_post_ancestors($_post);
  352. $_post = sanitize_post($_post, 'raw');
  353. wp_cache_add($_post->ID, $_post, 'posts');
  354. }
  355. }
  356. if ($filter != 'raw')
  357. $_post = sanitize_post($_post, $filter);
  358. if ( $output == OBJECT ) {
  359. return $_post;
  360. } elseif ( $output == ARRAY_A ) {
  361. $__post = get_object_vars($_post);
  362. return $__post;
  363. } elseif ( $output == ARRAY_N ) {
  364. $__post = array_values(get_object_vars($_post));
  365. return $__post;
  366. } else {
  367. return $_post;
  368. }
  369. }
  370. /**
  371. * Retrieve ancestors of a post.
  372. *
  373. * @since 2.5.0
  374. *
  375. * @param int|object $post Post ID or post object
  376. * @return array Ancestor IDs or empty array if none are found.
  377. */
  378. function get_post_ancestors($post) {
  379. $post = get_post($post);
  380. if ( !empty($post->ancestors) )
  381. return $post->ancestors;
  382. return array();
  383. }
  384. /**
  385. * Retrieve data from a post field based on Post ID.
  386. *
  387. * Examples of the post field will be, 'post_type', 'post_status', 'content',
  388. * etc and based off of the post object property or key names.
  389. *
  390. * The context values are based off of the taxonomy filter functions and
  391. * supported values are found within those functions.
  392. *
  393. * @since 2.3.0
  394. * @uses sanitize_post_field() See for possible $context values.
  395. *
  396. * @param string $field Post field name
  397. * @param id $post Post ID
  398. * @param string $context Optional. How to filter the field. Default is display.
  399. * @return WP_Error|string Value in post field or WP_Error on failure
  400. */
  401. function get_post_field( $field, $post, $context = 'display' ) {
  402. $post = (int) $post;
  403. $post = get_post( $post );
  404. if ( is_wp_error($post) )
  405. return $post;
  406. if ( !is_object($post) )
  407. return '';
  408. if ( !isset($post->$field) )
  409. return '';
  410. return sanitize_post_field($field, $post->$field, $post->ID, $context);
  411. }
  412. /**
  413. * Retrieve the mime type of an attachment based on the ID.
  414. *
  415. * This function can be used with any post type, but it makes more sense with
  416. * attachments.
  417. *
  418. * @since 2.0.0
  419. *
  420. * @param int $ID Optional. Post ID.
  421. * @return bool|string False on failure or returns the mime type
  422. */
  423. function get_post_mime_type($ID = '') {
  424. $post = & get_post($ID);
  425. if ( is_object($post) )
  426. return $post->post_mime_type;
  427. return false;
  428. }
  429. /**
  430. * Retrieve the format slug for a post
  431. *
  432. * @since 3.1.0
  433. *
  434. * @param int|object $post A post
  435. *
  436. * @return mixed The format if successful. False if no format is set. WP_Error if errors.
  437. */
  438. function get_post_format( $post = null ) {
  439. $post = get_post($post);
  440. if ( ! post_type_supports( $post->post_type, 'post-formats' ) )
  441. return false;
  442. $_format = get_the_terms( $post->ID, 'post_format' );
  443. if ( empty( $_format ) )
  444. return false;
  445. $format = array_shift( $_format );
  446. return ( str_replace('post-format-', '', $format->slug ) );
  447. }
  448. /**
  449. * Check if a post has a particular format
  450. *
  451. * @since 3.1.0
  452. * @uses has_term()
  453. *
  454. * @param string $format The format to check for
  455. * @param object|id $post The post to check. If not supplied, defaults to the current post if used in the loop.
  456. * @return bool True if the post has the format, false otherwise.
  457. */
  458. function has_post_format( $format, $post = null ) {
  459. return has_term('post-format-' . sanitize_key($format), 'post_format', $post);
  460. }
  461. /**
  462. * Assign a format to a post
  463. *
  464. * @since 3.1.0
  465. *
  466. * @param int|object $post The post for which to assign a format
  467. * @param string $format A format to assign. Use an empty string or array to remove all formats from the post.
  468. * @return mixed WP_Error on error. Array of affected term IDs on success.
  469. */
  470. function set_post_format( $post, $format ) {
  471. $post = get_post($post);
  472. if ( empty($post) )
  473. return new WP_Error('invalid_post', __('Invalid post'));
  474. if ( !empty($format) ) {
  475. $format = sanitize_key($format);
  476. if ( 'standard' == $format || !in_array( $format, array_keys( get_post_format_slugs() ) ) )
  477. $format = '';
  478. else
  479. $format = 'post-format-' . $format;
  480. }
  481. return wp_set_post_terms($post->ID, $format, 'post_format');
  482. }
  483. /**
  484. * Retrieve the post status based on the Post ID.
  485. *
  486. * If the post ID is of an attachment, then the parent post status will be given
  487. * instead.
  488. *
  489. * @since 2.0.0
  490. *
  491. * @param int $ID Post ID
  492. * @return string|bool Post status or false on failure.
  493. */
  494. function get_post_status($ID = '') {
  495. $post = get_post($ID);
  496. if ( !is_object($post) )
  497. return false;
  498. // Unattached attachments are assumed to be published.
  499. if ( ('attachment' == $post->post_type) && ('inherit' == $post->post_status) && ( 0 == $post->post_parent) )
  500. return 'publish';
  501. if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
  502. return get_post_status($post->post_parent);
  503. return $post->post_status;
  504. }
  505. /**
  506. * Retrieve all of the WordPress supported post statuses.
  507. *
  508. * Posts have a limited set of valid status values, this provides the
  509. * post_status values and descriptions.
  510. *
  511. * @since 2.5.0
  512. *
  513. * @return array List of post statuses.
  514. */
  515. function get_post_statuses( ) {
  516. $status = array(
  517. 'draft' => __('Draft'),
  518. 'pending' => __('Pending Review'),
  519. 'private' => __('Private'),
  520. 'publish' => __('Published')
  521. );
  522. return $status;
  523. }
  524. /**
  525. * Retrieve all of the WordPress support page statuses.
  526. *
  527. * Pages have a limited set of valid status values, this provides the
  528. * post_status values and descriptions.
  529. *
  530. * @since 2.5.0
  531. *
  532. * @return array List of page statuses.
  533. */
  534. function get_page_statuses( ) {
  535. $status = array(
  536. 'draft' => __('Draft'),
  537. 'private' => __('Private'),
  538. 'publish' => __('Published')
  539. );
  540. return $status;
  541. }
  542. /**
  543. * Register a post type. Do not use before init.
  544. *
  545. * A simple function for creating or modifying a post status based on the
  546. * parameters given. The function will accept an array (second optional
  547. * parameter), along with a string for the post status name.
  548. *
  549. *
  550. * Optional $args contents:
  551. *
  552. * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
  553. * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
  554. * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to true.
  555. * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
  556. * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
  557. * listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
  558. *
  559. * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
  560. *
  561. * @package WordPress
  562. * @subpackage Post
  563. * @since 3.0.0
  564. * @uses $wp_post_statuses Inserts new post status object into the list
  565. *
  566. * @param string $post_status Name of the post status.
  567. * @param array|string $args See above description.
  568. */
  569. function register_post_status($post_status, $args = array()) {
  570. global $wp_post_statuses;
  571. if (!is_array($wp_post_statuses))
  572. $wp_post_statuses = array();
  573. // Args prefixed with an underscore are reserved for internal use.
  574. $defaults = array('label' => false, 'label_count' => false, 'exclude_from_search' => null, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'hierarchical' => false, 'public' => null, 'internal' => null, 'protected' => null, 'private' => null, 'show_in_admin_all' => null, 'publicly_queryable' => null, 'show_in_admin_status_list' => null, 'show_in_admin_all_list' => null, 'single_view_cap' => null);
  575. $args = wp_parse_args($args, $defaults);
  576. $args = (object) $args;
  577. $post_status = sanitize_key($post_status);
  578. $args->name = $post_status;
  579. if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
  580. $args->internal = true;
  581. if ( null === $args->public )
  582. $args->public = false;
  583. if ( null === $args->private )
  584. $args->private = false;
  585. if ( null === $args->protected )
  586. $args->protected = false;
  587. if ( null === $args->internal )
  588. $args->internal = false;
  589. if ( null === $args->publicly_queryable )
  590. $args->publicly_queryable = $args->public;
  591. if ( null === $args->exclude_from_search )
  592. $args->exclude_from_search = $args->internal;
  593. if ( null === $args->show_in_admin_all_list )
  594. $args->show_in_admin_all_list = !$args->internal;
  595. if ( null === $args->show_in_admin_status_list )
  596. $args->show_in_admin_status_list = !$args->internal;
  597. if ( null === $args->single_view_cap )
  598. $args->single_view_cap = $args->public ? '' : 'edit';
  599. if ( false === $args->label )
  600. $args->label = $post_status;
  601. if ( false === $args->label_count )
  602. $args->label_count = array( $args->label, $args->label );
  603. $wp_post_statuses[$post_status] = $args;
  604. return $args;
  605. }
  606. /**
  607. * Retrieve a post status object by name
  608. *
  609. * @package WordPress
  610. * @subpackage Post
  611. * @since 3.0.0
  612. * @uses $wp_post_statuses
  613. * @see register_post_status
  614. * @see get_post_statuses
  615. *
  616. * @param string $post_status The name of a registered post status
  617. * @return object A post status object
  618. */
  619. function get_post_status_object( $post_status ) {
  620. global $wp_post_statuses;
  621. if ( empty($wp_post_statuses[$post_status]) )
  622. return null;
  623. return $wp_post_statuses[$post_status];
  624. }
  625. /**
  626. * Get a list of all registered post status objects.
  627. *
  628. * @package WordPress
  629. * @subpackage Post
  630. * @since 3.0.0
  631. * @uses $wp_post_statuses
  632. * @see register_post_status
  633. * @see get_post_status_object
  634. *
  635. * @param array|string $args An array of key => value arguments to match against the post status objects.
  636. * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
  637. * @param string $operator The logical operation to perform. 'or' means only one element
  638. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  639. * @return array A list of post type names or objects
  640. */
  641. function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
  642. global $wp_post_statuses;
  643. $field = ('names' == $output) ? 'name' : false;
  644. return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
  645. }
  646. /**
  647. * Whether the post type is hierarchical.
  648. *
  649. * A false return value might also mean that the post type does not exist.
  650. *
  651. * @since 3.0.0
  652. * @see get_post_type_object
  653. *
  654. * @param string $post_type Post type name
  655. * @return bool Whether post type is hierarchical.
  656. */
  657. function is_post_type_hierarchical( $post_type ) {
  658. if ( ! post_type_exists( $post_type ) )
  659. return false;
  660. $post_type = get_post_type_object( $post_type );
  661. return $post_type->hierarchical;
  662. }
  663. /**
  664. * Checks if a post type is registered.
  665. *
  666. * @since 3.0.0
  667. * @uses get_post_type_object()
  668. *
  669. * @param string $post_type Post type name
  670. * @return bool Whether post type is registered.
  671. */
  672. function post_type_exists( $post_type ) {
  673. return (bool) get_post_type_object( $post_type );
  674. }
  675. /**
  676. * Retrieve the post type of the current post or of a given post.
  677. *
  678. * @since 2.1.0
  679. *
  680. * @uses $post The Loop current post global
  681. *
  682. * @param mixed $the_post Optional. Post object or post ID.
  683. * @return bool|string post type or false on failure.
  684. */
  685. function get_post_type( $the_post = false ) {
  686. global $post;
  687. if ( false === $the_post )
  688. $the_post = $post;
  689. elseif ( is_numeric($the_post) )
  690. $the_post = get_post($the_post);
  691. if ( is_object($the_post) )
  692. return $the_post->post_type;
  693. return false;
  694. }
  695. /**
  696. * Retrieve a post type object by name
  697. *
  698. * @package WordPress
  699. * @subpackage Post
  700. * @since 3.0.0
  701. * @uses $wp_post_types
  702. * @see register_post_type
  703. * @see get_post_types
  704. *
  705. * @param string $post_type The name of a registered post type
  706. * @return object A post type object
  707. */
  708. function get_post_type_object( $post_type ) {
  709. global $wp_post_types;
  710. if ( empty($wp_post_types[$post_type]) )
  711. return null;
  712. return $wp_post_types[$post_type];
  713. }
  714. /**
  715. * Get a list of all registered post type objects.
  716. *
  717. * @package WordPress
  718. * @subpackage Post
  719. * @since 2.9.0
  720. * @uses $wp_post_types
  721. * @see register_post_type
  722. *
  723. * @param array|string $args An array of key => value arguments to match against the post type objects.
  724. * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
  725. * @param string $operator The logical operation to perform. 'or' means only one element
  726. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  727. * @return array A list of post type names or objects
  728. */
  729. function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
  730. global $wp_post_types;
  731. $field = ('names' == $output) ? 'name' : false;
  732. return wp_filter_object_list($wp_post_types, $args, $operator, $field);
  733. }
  734. /**
  735. * Register a post type. Do not use before init.
  736. *
  737. * A function for creating or modifying a post type based on the
  738. * parameters given. The function will accept an array (second optional
  739. * parameter), along with a string for the post type name.
  740. *
  741. * Optional $args contents:
  742. *
  743. * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
  744. * - description - A short descriptive summary of what the post type is. Defaults to blank.
  745. * - public - Whether posts of this type should be shown in the admin UI. Defaults to false.
  746. * - exclude_from_search - Whether to exclude posts with this post type from search results.
  747. * Defaults to true if the type is not public, false if the type is public.
  748. * - publicly_queryable - Whether post_type queries can be performed from the front page.
  749. * Defaults to whatever public is set as.
  750. * - show_ui - Whether to generate a default UI for managing this post type. Defaults to true
  751. * if the type is public, false if the type is not public.
  752. * - show_in_menu - Where to show the post type in the admin menu. True for a top level menu,
  753. * false for no menu, or can be a top level page like 'tools.php' or 'edit.php?post_type=page'.
  754. * show_ui must be true.
  755. * - menu_position - The position in the menu order the post type should appear. Defaults to the bottom.
  756. * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
  757. * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
  758. * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
  759. * capabilities, e.g. array('story', 'stories').
  760. * - capabilities - Array of capabilities for this post type. By default the capability_type is used
  761. * as a base to construct capabilities. You can see accepted values in {@link get_post_type_capabilities()}.
  762. * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
  763. * - hierarchical - Whether the post type is hierarchical. Defaults to false.
  764. * - supports - An alias for calling add_post_type_support() directly. See {@link add_post_type_support()}
  765. * for documentation. Defaults to none.
  766. * - register_meta_box_cb - Provide a callback function that will be called when setting up the
  767. * meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
  768. * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
  769. * Default is no taxonomies. Taxonomies can be registered later with register_taxonomy() or
  770. * register_taxonomy_for_object_type().
  771. * - labels - An array of labels for this post type. By default post labels are used for non-hierarchical
  772. * types and page labels for hierarchical ones. You can see accepted values in {@link get_post_type_labels()}.
  773. * - permalink_epmask - The default rewrite endpoint bitmasks.
  774. * - has_archive - True to enable post type archives. Will generate the proper rewrite rules if rewrite is enabled.
  775. * - rewrite - false to prevent rewrite. Defaults to true. Use array('slug'=>$slug) to customize permastruct;
  776. * default will use $post_type as slug. Other options include 'with_front', 'feeds', and 'pages'.
  777. * - query_var - false to prevent queries, or string to value of the query var to use for this post type
  778. * - can_export - true allows this post type to be exported.
  779. * - show_in_nav_menus - true makes this post type available for selection in navigation menus.
  780. * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
  781. * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
  782. *
  783. * @since 2.9.0
  784. * @uses $wp_post_types Inserts new post type object into the list
  785. *
  786. * @param string $post_type Name of the post type.
  787. * @param array|string $args See above description.
  788. * @return object|WP_Error the registered post type object, or an error object
  789. */
  790. function register_post_type($post_type, $args = array()) {
  791. global $wp_post_types, $wp_rewrite, $wp;
  792. if ( !is_array($wp_post_types) )
  793. $wp_post_types = array();
  794. // Args prefixed with an underscore are reserved for internal use.
  795. $defaults = array(
  796. 'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null,
  797. 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null,
  798. '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false,
  799. 'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true,
  800. 'supports' => array(), 'register_meta_box_cb' => null,
  801. 'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null,
  802. 'permalink_epmask' => EP_PERMALINK, 'can_export' => true, 'show_in_nav_menus' => null, 'show_in_menu' => null,
  803. );
  804. $args = wp_parse_args($args, $defaults);
  805. $args = (object) $args;
  806. $post_type = sanitize_key($post_type);
  807. $args->name = $post_type;
  808. if ( strlen( $post_type ) > 20 )
  809. return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
  810. // If not set, default to the setting for public.
  811. if ( null === $args->publicly_queryable )
  812. $args->publicly_queryable = $args->public;
  813. // If not set, default to the setting for public.
  814. if ( null === $args->show_ui )
  815. $args->show_ui = $args->public;
  816. // If not set, default to the setting for show_ui.
  817. if ( null === $args->show_in_menu || ! $args->show_ui )
  818. $args->show_in_menu = $args->show_ui;
  819. // Whether to show this type in nav-menus.php. Defaults to the setting for public.
  820. if ( null === $args->show_in_nav_menus )
  821. $args->show_in_nav_menus = $args->public;
  822. // If not set, default to true if not public, false if public.
  823. if ( null === $args->exclude_from_search )
  824. $args->exclude_from_search = !$args->public;
  825. // Back compat with quirky handling in version 3.0. #14122
  826. if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
  827. $args->map_meta_cap = true;
  828. if ( null === $args->map_meta_cap )
  829. $args->map_meta_cap = false;
  830. $args->cap = get_post_type_capabilities( $args );
  831. unset($args->capabilities);
  832. if ( is_array( $args->capability_type ) )
  833. $args->capability_type = $args->capability_type[0];
  834. if ( ! empty($args->supports) ) {
  835. add_post_type_support($post_type, $args->supports);
  836. unset($args->supports);
  837. } else {
  838. // Add default features
  839. add_post_type_support($post_type, array('title', 'editor'));
  840. }
  841. if ( false !== $args->query_var && !empty($wp) ) {
  842. if ( true === $args->query_var )
  843. $args->query_var = $post_type;
  844. $args->query_var = sanitize_title_with_dashes($args->query_var);
  845. $wp->add_query_var($args->query_var);
  846. }
  847. if ( false !== $args->rewrite && '' != get_option('permalink_structure') ) {
  848. if ( ! is_array( $args->rewrite ) )
  849. $args->rewrite = array();
  850. if ( empty( $args->rewrite['slug'] ) )
  851. $args->rewrite['slug'] = $post_type;
  852. if ( ! isset( $args->rewrite['with_front'] ) )
  853. $args->rewrite['with_front'] = true;
  854. if ( ! isset( $args->rewrite['pages'] ) )
  855. $args->rewrite['pages'] = true;
  856. if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
  857. $args->rewrite['feeds'] = (bool) $args->has_archive;
  858. if ( $args->hierarchical )
  859. $wp_rewrite->add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
  860. else
  861. $wp_rewrite->add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
  862. if ( $args->has_archive ) {
  863. $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
  864. $wp_rewrite->add_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
  865. if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
  866. $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
  867. $wp_rewrite->add_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
  868. $wp_rewrite->add_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
  869. }
  870. if ( $args->rewrite['pages'] )
  871. $wp_rewrite->add_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
  872. }
  873. $wp_rewrite->add_permastruct($post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite['with_front'], $args->permalink_epmask);
  874. }
  875. if ( $args->register_meta_box_cb )
  876. add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1);
  877. $args->labels = get_post_type_labels( $args );
  878. $args->label = $args->labels->name;
  879. $wp_post_types[$post_type] = $args;
  880. add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
  881. foreach ( $args->taxonomies as $taxonomy ) {
  882. register_taxonomy_for_object_type( $taxonomy, $post_type );
  883. }
  884. return $args;
  885. }
  886. /**
  887. * Builds an object with all post type capabilities out of a post type object
  888. *
  889. * Post type capabilities use the 'capability_type' argument as a base, if the
  890. * capability is not set in the 'capabilities' argument array or if the
  891. * 'capabilities' argument is not supplied.
  892. *
  893. * The capability_type argument can optionally be registered as an array, with
  894. * the first value being singular and the second plural, e.g. array('story, 'stories')
  895. * Otherwise, an 's' will be added to the value for the plural form. After
  896. * registration, capability_type will always be a string of the singular value.
  897. *
  898. * By default, seven keys are accepted as part of the capabilities array:
  899. *
  900. * - edit_post, read_post, and delete_post are meta capabilities, which are then
  901. * generally mapped to corresponding primitive capabilities depending on the
  902. * context, which would be the post being edited/read/deleted and the user or
  903. * role being checked. Thus these capabilities would generally not be granted
  904. * directly to users or roles.
  905. *
  906. * - edit_posts - Controls whether objects of this post type can be edited.
  907. * - edit_others_posts - Controls whether objects of this type owned by other users
  908. * can be edited. If the post type does not support an author, then this will
  909. * behave like edit_posts.
  910. * - publish_posts - Controls publishing objects of this post type.
  911. * - read_private_posts - Controls whether private objects can be read.
  912. * These four primitive capabilities are checked in core in various locations.
  913. * There are also seven other primitive capabilities which are not referenced
  914. * directly in core, except in map_meta_cap(), which takes the three aforementioned
  915. * meta capabilities and translates them into one or more primitive capabilities
  916. * that must then be checked against the user or role, depending on the context.
  917. *
  918. * - read - Controls whether objects of this post type can be read.
  919. * - delete_posts - Controls whether objects of this post type can be deleted.
  920. * - delete_private_posts - Controls whether private objects can be deleted.
  921. * - delete_published_posts - Controls whether published objects can be deleted.
  922. * - delete_others_posts - Controls whether objects owned by other users can be
  923. * can be deleted. If the post type does not support an author, then this will
  924. * behave like delete_posts.
  925. * - edit_private_posts - Controls whether private objects can be edited.
  926. * - edit_published_posts - Controls whether published objects can be deleted.
  927. *
  928. * These additional capabilities are only used in map_meta_cap(). Thus, they are
  929. * only assigned by default if the post type is registered with the 'map_meta_cap'
  930. * argument set to true (default is false).
  931. *
  932. * @see map_meta_cap()
  933. * @since 3.0.0
  934. *
  935. * @param object $args Post type registration arguments
  936. * @return object object with all the capabilities as member variables
  937. */
  938. function get_post_type_capabilities( $args ) {
  939. if ( ! is_array( $args->capability_type ) )
  940. $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
  941. // Singular base for meta capabilities, plural base for primitive capabilities.
  942. list( $singular_base, $plural_base ) = $args->capability_type;
  943. $default_capabilities = array(
  944. // Meta capabilities
  945. 'edit_post' => 'edit_' . $singular_base,
  946. 'read_post' => 'read_' . $singular_base,
  947. 'delete_post' => 'delete_' . $singular_base,
  948. // Primitive capabilities used outside of map_meta_cap():
  949. 'edit_posts' => 'edit_' . $plural_base,
  950. 'edit_others_posts' => 'edit_others_' . $plural_base,
  951. 'publish_posts' => 'publish_' . $plural_base,
  952. 'read_private_posts' => 'read_private_' . $plural_base,
  953. );
  954. // Primitive capabilities used within map_meta_cap():
  955. if ( $args->map_meta_cap ) {
  956. $default_capabilities_for_mapping = array(
  957. 'read' => 'read',
  958. 'delete_posts' => 'delete_' . $plural_base,
  959. 'delete_private_posts' => 'delete_private_' . $plural_base,
  960. 'delete_published_posts' => 'delete_published_' . $plural_base,
  961. 'delete_others_posts' => 'delete_others_' . $plural_base,
  962. 'edit_private_posts' => 'edit_private_' . $plural_base,
  963. 'edit_published_posts' => 'edit_published_' . $plural_base,
  964. );
  965. $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
  966. }
  967. $capabilities = array_merge( $default_capabilities, $args->capabilities );
  968. // Remember meta capabilities for future reference.
  969. if ( $args->map_meta_cap )
  970. _post_type_meta_capabilities( $capabilities );
  971. return (object) $capabilities;
  972. }
  973. /**
  974. * Stores or returns a list of post type meta caps for map_meta_cap().
  975. *
  976. * @since 3.1.0
  977. * @access private
  978. */
  979. function _post_type_meta_capabilities( $capabilities = null ) {
  980. static $meta_caps = array();
  981. if ( null === $capabilities )
  982. return $meta_caps;
  983. foreach ( $capabilities as $core => $custom ) {
  984. if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
  985. $meta_caps[ $custom ] = $core;
  986. }
  987. }
  988. /**
  989. * Builds an object with all post type labels out of a post type object
  990. *
  991. * Accepted keys of the label array in the post type object:
  992. * - name - general name for the post type, usually plural. The same and overriden by $post_type_object->label. Default is Posts/Pages
  993. * - singular_name - name for one object of this post type. Default is Post/Page
  994. * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code>
  995. * - add_new_item - Default is Add New Post/Add New Page
  996. * - edit_item - Default is Edit Post/Edit Page
  997. * - new_item - Default is New Post/New Page
  998. * - view_item - Default is View Post/View Page
  999. * - search_items - Default is Search Posts/Search Pages
  1000. * - not_found - Default is No posts found/No pages found
  1001. * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
  1002. * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
  1003. *
  1004. * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
  1005. *
  1006. * @since 3.0.0
  1007. * @param object $post_type_object
  1008. * @return object object with all the labels as member variables
  1009. */
  1010. function get_post_type_labels( $post_type_object ) {
  1011. $nohier_vs_hier_defaults = array(
  1012. 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
  1013. 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
  1014. 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
  1015. 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
  1016. 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
  1017. 'new_item' => array( __('New Post'), __('New Page') ),
  1018. 'view_item' => array( __('View Post'), __('View Page') ),
  1019. 'search_items' => array( __('Search Posts'), __('Search Pages') ),
  1020. 'not_found' => array( __('No posts found.'), __('No pages found.') ),
  1021. 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
  1022. 'parent_item_colon' => array( null, __('Parent Page:') ),
  1023. );
  1024. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  1025. return _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
  1026. }
  1027. /**
  1028. * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
  1029. *
  1030. * @access private
  1031. * @since 3.0.0
  1032. */
  1033. function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
  1034. if ( isset( $object->label ) && empty( $object->labels['name'] ) )
  1035. $object->labels['name'] = $object->label;
  1036. if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
  1037. $object->labels['singular_name'] = $object->labels['name'];
  1038. if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
  1039. $object->labels['menu_name'] = $object->labels['name'];
  1040. foreach ( $nohier_vs_hier_defaults as $key => $value )
  1041. $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
  1042. $labels = array_merge( $defaults, $object->labels );
  1043. return (object)$labels;
  1044. }
  1045. /**
  1046. * Adds submenus for post types.
  1047. *
  1048. * @access private
  1049. * @since 3.1.0
  1050. */
  1051. function _add_post_type_submenus() {
  1052. foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
  1053. $ptype_obj = get_post_type_object( $ptype );
  1054. // Submenus only.
  1055. if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
  1056. continue;
  1057. add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->menu_name, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
  1058. }
  1059. }
  1060. add_action( 'admin_menu', '_add_post_type_submenus' );
  1061. /**
  1062. * Register support of certain features for a post type.
  1063. *
  1064. * All features are directly associated with a functional area of the edit screen, such as the
  1065. * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
  1066. * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
  1067. *
  1068. * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
  1069. * and the 'comments' feature dicates whether the comments count will show on the edit screen.
  1070. *
  1071. * @since 3.0.0
  1072. * @param string $post_type The post type for which to add the feature
  1073. * @param string|array $feature the feature being added, can be an array of feature strings or a single string
  1074. */
  1075. function add_post_type_support( $post_type, $feature ) {
  1076. global $_wp_post_type_features;
  1077. $features = (array) $feature;
  1078. foreach ($features as $feature) {
  1079. if ( func_num_args() == 2 )
  1080. $_wp_post_type_features[$post_type][$feature] = true;
  1081. else
  1082. $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
  1083. }
  1084. }
  1085. /**
  1086. * Remove support for a feature from a post type.
  1087. *
  1088. * @since 3.0.0
  1089. * @param string $post_type The post type for which to remove the feature
  1090. * @param string $feature The feature being removed
  1091. */
  1092. function remove_post_type_support( $post_type, $feature ) {
  1093. global $_wp_post_type_features;
  1094. if ( !isset($_wp_post_type_features[$post_type]) )
  1095. return;
  1096. if ( isset($_wp_post_type_features[$post_type][$feature]) )
  1097. unset($_wp_post_type_features[$post_type][$feature]);
  1098. }
  1099. /**
  1100. * Checks a post type's support for a given feature
  1101. *
  1102. * @since 3.0.0
  1103. * @param string $post_type The post type being checked
  1104. * @param string $feature the feature being checked
  1105. * @return boolean
  1106. */
  1107. function post_type_supports( $post_type, $feature ) {
  1108. global $_wp_post_type_features;
  1109. if ( !isset( $_wp_post_type_features[$post_type][$feature] ) )
  1110. return false;
  1111. // If no args passed then no extra checks need be performed
  1112. if ( func_num_args() <= 2 )
  1113. return true;
  1114. // @todo Allow pluggable arg checking
  1115. //$args = array_slice( func_get_args(), 2 );
  1116. return true;
  1117. }
  1118. /**
  1119. * Updates the post type for the post ID.
  1120. *
  1121. * The page or post cache will be cleaned for the post ID.
  1122. *
  1123. * @since 2.5.0
  1124. *
  1125. * @uses $wpdb
  1126. *
  1127. * @param int $post_id Post ID to change post type. Not actually optional.
  1128. * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
  1129. * name a few.
  1130. * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
  1131. */
  1132. function set_post_type( $post_id = 0, $post_type = 'post' ) {
  1133. global $wpdb;
  1134. $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
  1135. $return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
  1136. if ( 'page' == $post_type )
  1137. clean_page_cache($post_id);
  1138. else
  1139. clean_post_cache($post_id);
  1140. return $return;
  1141. }
  1142. /**
  1143. * Retrieve list of latest posts or posts matching criteria.
  1144. *
  1145. * The defaults are as follows:
  1146. * 'numberposts' - Default is 5. Total number of posts to retrieve.
  1147. * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
  1148. * 'category' - What category to pull the posts from.
  1149. * 'orderby' - Default is 'post_date'. How to order the posts.
  1150. * 'order' - Default is 'DESC'. The order to retrieve the posts.
  1151. * 'include' - See {@link WP_Query::query()} for more.
  1152. * 'exclude' - See {@link WP_Query::query()} for more.
  1153. * 'meta_key' - See {@link WP_Query::query()} for more.
  1154. * 'meta_value' - See {@link WP_Query::query()} for more.
  1155. * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
  1156. * 'post_parent' - The parent of the post or post type.
  1157. * 'post_status' - Default is 'published'. Post status to retrieve.
  1158. *
  1159. * @since 1.2.0
  1160. * @uses $wpdb
  1161. * @uses WP_Query::query() See for more default arguments and information.
  1162. * @link http://codex.wordpress.org/Template_Tags/get_posts
  1163. *
  1164. * @param array $args Optional. Overrides defaults.
  1165. * @return array List of posts.
  1166. */
  1167. function get_posts($args = null) {
  1168. $defaults = array(
  1169. 'numberposts' => 5, 'offset' => 0,
  1170. 'category' => 0, 'orderby' => 'post_date',
  1171. 'order' => 'DESC', 'include' => array(),
  1172. 'exclude' => array(), 'meta_key' => '',
  1173. 'meta_value' =>'', 'post_type' => 'post',
  1174. 'suppress_filters' => true
  1175. );
  1176. $r = wp_parse_args( $args, $defaults );
  1177. if ( empty( $r['post_status'] ) )
  1178. $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
  1179. if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
  1180. $r['posts_per_page'] = $r['numberposts'];
  1181. if ( ! empty($r['category']) )
  1182. $r['cat'] = $r['category'];
  1183. if ( ! empty($r['include']) ) {
  1184. $incposts = wp_parse_id_list( $r['include'] );
  1185. $r['posts_per_page'] = count($incposts); // only the number of posts included
  1186. $r['post__in'] = $incposts;
  1187. } elseif ( ! empty($r['exclude']) )
  1188. $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
  1189. $r['ignore_sticky_posts'] = true;
  1190. $r['no_found_rows'] = true;
  1191. $get_posts = new WP_Query;
  1192. return $get_posts->query($r);
  1193. }
  1194. //
  1195. // Post meta functions
  1196. //
  1197. /**
  1198. * Add meta data field to a post.
  1199. *
  1200. * Post meta data is called "Custom Fields" on the Administration Panels.
  1201. *
  1202. * @since 1.5.0
  1203. * @uses $wpdb
  1204. * @link http://codex.wordpress.org/Function_Reference/add_post_meta
  1205. *
  1206. * @param int $post_id Post ID.
  1207. * @param string $meta_key Metadata name.
  1208. * @param mixed $meta_value Metadata value.
  1209. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  1210. * @return bool False for failure. True for success.
  1211. */
  1212. function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
  1213. // make sure meta is added to the post, not a revision
  1214. if ( $the_post = wp_is_post_revision($post_id) )
  1215. $post_id = $the_post;
  1216. return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
  1217. }
  1218. /**
  1219. * Remove metadata matching criteria from a post.
  1220. *
  1221. * You can match based on the key, or key and value. Removing based on key and
  1222. * value, will keep from removing duplicate metadata with the same key. It also
  1223. * allows removing all metadata matching key, if needed.
  1224. *
  1225. * @since 1.5.0
  1226. * @uses $wpdb
  1227. * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
  1228. *
  1229. * @param int $post_id post ID
  1230. * @param string $meta_key Metadata name.
  1231. * @param mixed $meta_value Optional. Metadata value.
  1232. * @return bool False for failure. True for success.
  1233. */
  1234. function delete_post_meta($post_id, $meta_key, $meta_value = '') {
  1235. // make sure meta is added to the post, not a revision
  1236. if ( $the_post = wp_is_post_revision($post_id) )
  1237. $post_id = $the_post;
  1238. return delete_metadata('post', $post_id, $meta_key, $meta_value);
  1239. }
  1240. /**
  1241. * Retrieve post meta field for a post.
  1242. *
  1243. * @since 1.5.0
  1244. * @uses $wpdb
  1245. * @link http://codex.wordpress.org/Function_Reference/get_post_meta
  1246. *
  1247. * @param int $post_id Post ID.
  1248. * @param string $key The meta key to retrieve.
  1249. * @param bool $single Whether to return a single value.
  1250. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  1251. * is true.
  1252. */
  1253. function get_post_meta($post_id, $key, $single = false) {
  1254. return get_metadata('post', $post_id, $key, $single);
  1255. }
  1256. /**
  1257. * Update post meta field based on post ID.
  1258. *
  1259. * Use the $prev_value parameter to differentiate between meta fields with the
  1260. * same key and post ID.
  1261. *
  1262. * If the meta field for the post does not exist, it will be added.
  1263. *
  1264. * @since 1.5.0
  1265. * @uses $wpdb
  1266. * @link http://codex.wordpress.org/Function_Reference/update_post_meta
  1267. *
  1268. * @param int $post_id Post ID.
  1269. * @param string $meta_key Metadata key.
  1270. * @param mixed $meta_value Metadata value.
  1271. * @param mixed $prev_value Optional. Previous value to check before removing.
  1272. * @return bool False on failure, true if success.
  1273. */
  1274. function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
  1275. // make sure meta is added to the post, not a revision
  1276. if ( $the_post = wp_is_post_revision($post_id) )
  1277. $post_id = $the_post;
  1278. return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
  1279. }
  1280. /**
  1281. * Delete everything from post meta matching meta key.
  1282. *
  1283. * @since 2.3.0
  1284. * @uses $wpdb
  1285. *
  1286. * @param string $post_meta_key Key to search for when deleting.
  1287. * @return bool Whether the post meta key was deleted from the database
  1288. */
  1289. function delete_post_meta_by_key($post_meta_key) {
  1290. if ( !$post_meta_key )
  1291. return false;
  1292. global $wpdb;
  1293. $post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
  1294. if ( $post_ids ) {
  1295. $postmetaids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key ) );
  1296. $in = implode( ',', array_fill(1, count($postmetaids), '%d'));
  1297. do_action( 'delete_postmeta', $postmetaids );
  1298. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN($in)", $postmetaids ));
  1299. do_action( 'deleted_postmeta', $postmetaids );
  1300. foreach ( $post_ids as $post_id )
  1301. wp_cache_delete($post_id, 'post_meta');
  1302. return true;
  1303. }
  1304. return false;
  1305. }
  1306. /**
  1307. * Retrieve post meta fields, based on post ID.
  1308. *
  1309. * The post meta fields are retrieved from the cache, so the function is
  1310. * optimized to be called more than once. It also applies to the functions, that
  1311. * use this function.
  1312. *
  1313. * @since 1.2.0
  1314. * @link http://codex.wordpress.org/Function_Reference/get_post_custom
  1315. *
  1316. * @uses $id Current Loop Post ID
  1317. *
  1318. * @param int $post_id post ID
  1319. * @return array
  1320. */
  1321. function get_post_custom( $post_id = 0 ) {
  1322. $post_id = absint( $post_id );
  1323. if ( ! $post_id )
  1324. $post_id = get_the_ID();
  1325. if ( ! wp_cache_get( $post_id, 'post_meta' ) )
  1326. update_postmeta_cache( $post_id );
  1327. return wp_cache_get( $post_id, 'post_meta' );
  1328. }
  1329. /**
  1330. * Retrieve meta field names for a post.
  1331. *
  1332. * If there are no meta fields, then nothing (null) will be returned.
  1333. *
  1334. * @since 1.2.0
  1335. * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
  1336. *
  1337. * @param int $post_id post ID
  1338. * @return array|null Either array of the keys, or null if keys could not be retrieved.
  1339. */
  1340. function get_post_custom_keys( $post_id = 0 ) {
  1341. $custom = get_post_custom( $post_id );
  1342. if ( !is_array($custom) )
  1343. return;
  1344. if ( $keys = array_keys($custom) )
  1345. return $keys;
  1346. }
  1347. /**
  1348. * Retrieve values for a custom post field.
  1349. *
  1350. * The parameters must not be considered optional. All of the post meta fields
  1351. * will be retrieved and only the meta field key values returned.
  1352. *
  1353. * @since 1.2.0
  1354. * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
  1355. *
  1356. * @param string $key Meta field key.
  1357. * @param int $post_id Post ID
  1358. * @return array Meta field values.
  1359. */
  1360. function get_post_custom_values( $key = '', $post_id = 0 ) {
  1361. if ( !$key )
  1362. return null;
  1363. $custom = get_post_custom($post_id);
  1364. return isset($custom[$key]) ? $custom[$key] : null;
  1365. }
  1366. /**
  1367. * Check if post is sticky.
  1368. *
  1369. * Sticky posts should remain at the top of The Loop. If the post ID is not
  1370. * given, then The Loop ID for the current post will be used.
  1371. *
  1372. * @since 2.7.0
  1373. *
  1374. * @param int $post_id Optional. Post ID.
  1375. * @return bool Whether post is sticky.
  1376. */
  1377. function is_sticky( $post_id = 0 ) {
  1378. $post_id = absint( $post_id );
  1379. if ( ! $post_id )
  1380. $post_id = get_the_ID();
  1381. $stickies = get_option( 'sticky_posts' );
  1382. if ( ! is_array( $stickies ) )
  1383. return false;
  1384. if ( in_array( $post_id, $stickies ) )
  1385. return true;
  1386. return false;
  1387. }
  1388. /**
  1389. * Sanitize every post field.
  1390. *
  1391. * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
  1392. *
  1393. * @since 2.3.0
  1394. * @uses sanitize_post_field() Used to sanitize the fields.
  1395. *
  1396. * @param object|array $post The Post Object or Array
  1397. * @param string $context Optional, default is 'display'. How to sanitize post fields.
  1398. * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
  1399. */
  1400. function sanitize_post($post, $context = 'display') {
  1401. if ( is_object($post) ) {
  1402. // Check if post already filtered for this context
  1403. if ( isset($post->filter) && $context == $post->filter )
  1404. return $post;
  1405. if ( !isset($post->ID) )
  1406. $post->ID = 0;
  1407. foreach ( array_keys(get_object_vars($post)) as $field )
  1408. $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
  1409. $post->filter = $context;
  1410. } else {
  1411. // Check if post already filtered for this context
  1412. if ( isset($post['filter']) && $context == $post['filter'] )
  1413. return $post;
  1414. if ( !isset($post['ID']) )
  1415. $post['ID'] = 0;
  1416. foreach ( array_keys($post) as $field )
  1417. $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
  1418. $post['filter'] = $context;
  1419. }
  1420. return $post;
  1421. }
  1422. /**
  1423. * Sanitize post field based on context.
  1424. *
  1425. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1426. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1427. * when calling filters.
  1428. *
  1429. * @since 2.3.0
  1430. * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
  1431. * $post_id if $context == 'edit' and field name prefix == 'post_'.
  1432. *
  1433. * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
  1434. * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
  1435. * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
  1436. *
  1437. * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
  1438. * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
  1439. * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
  1440. * 'edit' and 'db' and field name prefix != 'post_'.
  1441. *
  1442. * @param string $field The Post Object field name.
  1443. * @param mixed $value The Post Object value.
  1444. * @param int $post_id Post ID.
  1445. * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
  1446. * 'attribute' and 'js'.
  1447. * @return mixed Sanitized value.
  1448. */
  1449. function sanitize_post_field($field, $value, $post_id, $context) {
  1450. $int_fields = array('ID', 'post_parent', 'menu_order');
  1451. if ( in_array($field, $int_fields) )
  1452. $value = (int) $value;
  1453. // Fields which contain arrays of ints.
  1454. $array_int_fields = array( 'ancestors' );
  1455. if ( in_array($field, $array_int_fields) ) {
  1456. $value = array_map( 'absint', $value);
  1457. return $value;
  1458. }
  1459. if ( 'raw' == $context )
  1460. return $value;
  1461. $prefixed = false;
  1462. if ( false !== strpos($field, 'post_') ) {
  1463. $prefixed = true;
  1464. $field_no_prefix = str_replace('post_', '', $field);
  1465. }
  1466. if ( 'edit' == $context ) {
  1467. $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
  1468. if ( $prefixed ) {
  1469. $value = apply_filters("edit_{$field}", $value, $post_id);
  1470. // Old school
  1471. $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
  1472. } else {
  1473. $value = apply_filters("edit_post_{$field}", $value, $post_id);
  1474. }
  1475. if ( in_array($field, $format_to_edit) ) {
  1476. if ( 'post_content' == $field )
  1477. $value = format_to_edit($value, user_can_richedit());
  1478. else
  1479. $value = format_to_edit($value);
  1480. } else {
  1481. $value = esc_attr($value);
  1482. }
  1483. } else if ( 'db' == $context ) {
  1484. if ( $prefixed ) {
  1485. $value = apply_filters("pre_{$field}", $value);
  1486. $value = apply_filters("{$field_no_prefix}_save_pre", $value);
  1487. } else {
  1488. $value = apply_filters("pre_post_{$field}", $value);
  1489. $value = apply_filters("{$field}_pre", $value);
  1490. }
  1491. } else {
  1492. // Use display filters by default.
  1493. if ( $prefixed )
  1494. $value = apply_filters($field, $value, $post_id, $context);
  1495. else
  1496. $value = apply_filters("post_{$field}", $value, $post_id, $context);
  1497. }
  1498. if ( 'attribute' == $context )
  1499. $value = esc_attr($value);
  1500. else if ( 'js' == $context )
  1501. $value = esc_js($value);
  1502. return $value;
  1503. }
  1504. /**
  1505. * Make a post sticky.
  1506. *
  1507. * Sticky posts should be displayed at the top of the front page.
  1508. *
  1509. * @since 2.7.0
  1510. *
  1511. * @param int $post_id Post ID.
  1512. */
  1513. function stick_post($post_id) {
  1514. $stickies = get_option('sticky_posts');
  1515. if ( !is_array($stickies) )
  1516. $stickies = array($post_id);
  1517. if ( ! in_array($post_id, $stickies) )
  1518. $stickies[] = $post_id;
  1519. update_option('sticky_posts', $stickies);
  1520. }
  1521. /**
  1522. * Unstick a post.
  1523. *
  1524. * Sticky posts should be displayed at the top of the front page.
  1525. *
  1526. * @since 2.7.0
  1527. *
  1528. * @param int $post_id Post ID.
  1529. */
  1530. function unstick_post($post_id) {
  1531. $stickies = get_option('sticky_posts');
  1532. if ( !is_array($stickies) )
  1533. return;
  1534. if ( ! in_array($post_id, $stickies) )
  1535. return;
  1536. $offset = array_search($post_id, $stickies);
  1537. if ( false === $offset )
  1538. return;
  1539. array_splice($stickies, $offset, 1);
  1540. update_option('sticky_posts', $stickies);
  1541. }
  1542. /**
  1543. * Count number of posts of a post type and is user has permissions to view.
  1544. *
  1545. * This function provides an efficient method of finding the amount of post's
  1546. * type a blog has. Another method is to count the amount of items in
  1547. * get_posts(), but that method has a lot of overhead with doing so. Therefore,
  1548. * when developing for 2.5+, use this function instead.
  1549. *
  1550. * The $perm parameter checks for 'readable' value and if the user can read
  1551. * private posts, it will display that for the user that is signed in.
  1552. *
  1553. * @since 2.5.0
  1554. * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
  1555. *
  1556. * @param string $type Optional. Post type to retrieve count
  1557. * @param string $perm Optional. 'readable' or empty.
  1558. * @return object Number of posts for each status
  1559. */
  1560. function wp_count_posts( $type = 'post', $perm = '' ) {
  1561. global $wpdb;
  1562. $user = wp_get_current_user();
  1563. $cache_key = $type;
  1564. $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
  1565. if ( 'readable' == $perm && is_user_logged_in() ) {
  1566. $post_type_object = get_post_type_object($type);
  1567. if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
  1568. $cache_key .= '_' . $perm . '_' . $user->ID;
  1569. $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
  1570. }
  1571. }
  1572. $query .= ' GROUP BY post_status';
  1573. $count = wp_cache_get($cache_key, 'counts');
  1574. if ( false !== $count )
  1575. return $count;
  1576. $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
  1577. $stats = array();
  1578. foreach ( get_post_stati() as $state )
  1579. $stats[$state] = 0;
  1580. foreach ( (array) $count as $row )
  1581. $stats[$row['post_status']] = $row['num_posts'];
  1582. $stats = (object) $stats;
  1583. wp_cache_set($cache_key, $stats, 'counts');
  1584. return $stats;
  1585. }
  1586. /**
  1587. * Count number of attachments for the mime type(s).
  1588. *
  1589. * If you set the optional mime_type parameter, then an array will still be
  1590. * returned, but will only have the item you are looking for. It does not give
  1591. * you the number of attachments that are children of a post. You can get that
  1592. * by counting the number of children that post has.
  1593. *
  1594. * @since 2.5.0
  1595. *
  1596. * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
  1597. * @return array Number of posts for each mime type.
  1598. */
  1599. function wp_count_attachments( $mime_type = '' ) {
  1600. global $wpdb;
  1601. $and = wp_post_mime_type_where( $mime_type );
  1602. $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
  1603. $stats = array( );
  1604. foreach( (array) $count as $row ) {
  1605. $stats[$row['post_mime_type']] = $row['num_posts'];
  1606. }
  1607. $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
  1608. return (object) $stats;
  1609. }
  1610. /**
  1611. * Check a MIME-Type against a list.
  1612. *
  1613. * If the wildcard_mime_types parameter is a string, it must be comma separated
  1614. * list. If the real_mime_types is a string, it is also comma separated to
  1615. * create the list.
  1616. *
  1617. * @since 2.5.0
  1618. *
  1619. * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
  1620. * flash (same as *flash*).
  1621. * @param string|array $real_mime_types post_mime_type values
  1622. * @return array array(wildcard=>array(real types))
  1623. */
  1624. function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
  1625. $matches = array();
  1626. if ( is_string($wildcard_mime_types) )
  1627. $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
  1628. if ( is_string($real_mime_types) )
  1629. $real_mime_types = array_map('trim', explode(',', $real_mime_types));
  1630. $wild = '[-._a-z0-9]*';
  1631. foreach ( (array) $wildcard_mime_types as $type ) {
  1632. $type = str_replace('*', $wild, $type);
  1633. $patternses[1][$type] = "^$type$";
  1634. if ( false === strpos($type, '/') ) {
  1635. $patternses[2][$type] = "^$type/";
  1636. $patternses[3][$type] = $type;
  1637. }
  1638. }
  1639. asort($patternses);
  1640. foreach ( $patternses as $patterns )
  1641. foreach ( $patterns as $type => $pattern )
  1642. foreach ( (array) $real_mime_types as $real )
  1643. if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
  1644. $matches[$type][] = $real;
  1645. return $matches;
  1646. }
  1647. /**
  1648. * Convert MIME types into SQL.
  1649. *
  1650. * @since 2.5.0
  1651. *
  1652. * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
  1653. * @param string $table_alias Optional. Specify a table alias, if needed.
  1654. * @return string The SQL AND clause for mime searching.
  1655. */
  1656. function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
  1657. $where = '';
  1658. $wildcards = array('', '%', '%/%');
  1659. if ( is_string($post_mime_types) )
  1660. $post_mime_types = array_map('trim', explode(',', $post_mime_types));
  1661. foreach ( (array) $post_mime_types as $mime_type ) {
  1662. $mime_type = preg_replace('/\s/', '', $mime_type);
  1663. $slashpos = strpos($mime_type, '/');
  1664. if ( false !== $slashpos ) {
  1665. $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
  1666. $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
  1667. if ( empty($mime_subgroup) )
  1668. $mime_subgroup = '*';
  1669. else
  1670. $mime_subgroup = str_replace('/', '', $mime_subgroup);
  1671. $mime_pattern = "$mime_group/$mime_subgroup";
  1672. } else {
  1673. $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
  1674. if ( false === strpos($mime_pattern, '*') )
  1675. $mime_pattern .= '/*';
  1676. }
  1677. $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
  1678. if ( in_array( $mime_type, $wildcards ) )
  1679. return '';
  1680. if ( false !== strpos($mime_pattern, '%') )
  1681. $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
  1682. else
  1683. $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
  1684. }
  1685. if ( !empty($wheres) )
  1686. $where = ' AND (' . join(' OR ', $wheres) . ') ';
  1687. return $where;
  1688. }
  1689. /**
  1690. * Trashes or deletes a post or page.
  1691. *
  1692. * When the post and page is permanently deleted, everything that is tied to it is deleted also.
  1693. * This includes comments, post meta fields, and terms associated with the post.
  1694. *
  1695. * The post or page is moved to trash instead of permanently deleted unless trash is
  1696. * disabled, item is already in the trash, or $force_delete is true.
  1697. *
  1698. * @since 1.0.0
  1699. * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
  1700. * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
  1701. * @uses wp_delete_attachment() if post type is 'attachment'.
  1702. * @uses wp_trash_post() if item should be trashed.
  1703. *
  1704. * @param int $postid Post ID.
  1705. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  1706. * @return mixed False on failure
  1707. */
  1708. function wp_delete_post( $postid = 0, $force_delete = false ) {
  1709. global $wpdb, $wp_rewrite;
  1710. if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
  1711. return $post;
  1712. if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
  1713. return wp_trash_post($postid);
  1714. if ( $post->post_type == 'attachment' )
  1715. return wp_delete_attachment( $postid, $force_delete );
  1716. do_action('delete_post', $postid);
  1717. delete_post_meta($postid,'_wp_trash_meta_status');
  1718. delete_post_meta($postid,'_wp_trash_meta_time');
  1719. wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
  1720. $parent_data = array( 'post_parent' => $post->post_parent );
  1721. $parent_where = array( 'post_parent' => $postid );
  1722. if ( 'page' == $post->post_type) {
  1723. // if the page is defined in option page_on_front or post_for_posts,
  1724. // adjust the corresponding options
  1725. if ( get_option('page_on_front') == $postid ) {
  1726. update_option('show_on_front', 'posts');
  1727. delete_option('page_on_front');
  1728. }
  1729. if ( get_option('page_for_posts') == $postid ) {
  1730. delete_option('page_for_posts');
  1731. }
  1732. // Point children of this page to its parent, also clean the cache of affected children
  1733. $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
  1734. $children = $wpdb->get_results($children_query);
  1735. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
  1736. } else {
  1737. unstick_post($postid);
  1738. }
  1739. // Do raw query. wp_get_post_revisions() is filtered
  1740. $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
  1741. // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
  1742. foreach ( $revision_ids as $revision_id )
  1743. wp_delete_post_revision( $revision_id );
  1744. // Point all attachments to this post up one level
  1745. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
  1746. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
  1747. if ( ! empty($comment_ids) ) {
  1748. do_action( 'delete_comment', $comment_ids );
  1749. foreach ( $comment_ids as $comment_id )
  1750. wp_delete_comment( $comment_id, true );
  1751. do_action( 'deleted_comment', $comment_ids );
  1752. }
  1753. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
  1754. if ( !empty($post_meta_ids) ) {
  1755. do_action( 'delete_postmeta', $post_meta_ids );
  1756. $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
  1757. $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
  1758. do_action( 'deleted_postmeta', $post_meta_ids );
  1759. }
  1760. do_action( 'delete_post', $postid );
  1761. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
  1762. do_action( 'deleted_post', $postid );
  1763. if ( 'page' == $post->post_type ) {
  1764. clean_page_cache($postid);
  1765. foreach ( (array) $children as $child )
  1766. clean_page_cache($child->ID);
  1767. $wp_rewrite->flush_rules(false);
  1768. } else {
  1769. clean_post_cache($postid);
  1770. }
  1771. wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
  1772. do_action('deleted_post', $postid);
  1773. return $post;
  1774. }
  1775. /**
  1776. * Moves a post or page to the Trash
  1777. *
  1778. * If trash is disabled, the post or page is permanently deleted.
  1779. *
  1780. * @since 2.9.0
  1781. * @uses do_action() on 'trash_post' before trashing
  1782. * @uses do_action() on 'trashed_post' after trashing
  1783. * @uses wp_delete_post() if trash is disabled
  1784. *
  1785. * @param int $post_id Post ID.
  1786. * @return mixed False on failure
  1787. */
  1788. function wp_trash_post($post_id = 0) {
  1789. if ( !EMPTY_TRASH_DAYS )
  1790. return wp_delete_post($post_id, true);
  1791. if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1792. return $post;
  1793. if ( $post['post_status'] == 'trash' )
  1794. return false;
  1795. do_action('trash_post', $post_id);
  1796. add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
  1797. add_post_meta($post_id,'_wp_trash_meta_time', time());
  1798. $post['post_status'] = 'trash';
  1799. wp_insert_post($post);
  1800. wp_trash_post_comments($post_id);
  1801. do_action('trashed_post', $post_id);
  1802. return $post;
  1803. }
  1804. /**
  1805. * Restores a post or page from the Trash
  1806. *
  1807. * @since 2.9.0
  1808. * @uses do_action() on 'untrash_post' before undeletion
  1809. * @uses do_action() on 'untrashed_post' after undeletion
  1810. *
  1811. * @param int $post_id Post ID.
  1812. * @return mixed False on failure
  1813. */
  1814. function wp_untrash_post($post_id = 0) {
  1815. if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1816. return $post;
  1817. if ( $post['post_status'] != 'trash' )
  1818. return false;
  1819. do_action('untrash_post', $post_id);
  1820. $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
  1821. $post['post_status'] = $post_status;
  1822. delete_post_meta($post_id, '_wp_trash_meta_status');
  1823. delete_post_meta($post_id, '_wp_trash_meta_time');
  1824. wp_insert_post($post);
  1825. wp_untrash_post_comments($post_id);
  1826. do_action('untrashed_post', $post_id);
  1827. return $post;
  1828. }
  1829. /**
  1830. * Moves comments for a post to the trash
  1831. *
  1832. * @since 2.9.0
  1833. * @uses do_action() on 'trash_post_comments' before trashing
  1834. * @uses do_action() on 'trashed_post_comments' after trashing
  1835. *
  1836. * @param int $post Post ID or object.
  1837. * @return mixed False on failure
  1838. */
  1839. function wp_trash_post_comments($post = null) {
  1840. global $wpdb;
  1841. $post = get_post($post);
  1842. if ( empty($post) )
  1843. return;
  1844. $post_id = $post->ID;
  1845. do_action('trash_post_comments', $post_id);
  1846. $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
  1847. if ( empty($comments) )
  1848. return;
  1849. // Cache current status for each comment
  1850. $statuses = array();
  1851. foreach ( $comments as $comment )
  1852. $statuses[$comment->comment_ID] = $comment->comment_approved;
  1853. add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
  1854. // Set status for all comments to post-trashed
  1855. $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
  1856. clean_comment_cache( array_keys($statuses) );
  1857. do_action('trashed_post_comments', $post_id, $statuses);
  1858. return $result;
  1859. }
  1860. /**
  1861. * Restore comments for a post from the trash
  1862. *
  1863. * @since 2.9.0
  1864. * @uses do_action() on 'untrash_post_comments' before trashing
  1865. * @uses do_action() on 'untrashed_post_comments' after trashing
  1866. *
  1867. * @param int $post Post ID or object.
  1868. * @return mixed False on failure
  1869. */
  1870. function wp_untrash_post_comments($post = null) {
  1871. global $wpdb;
  1872. $post = get_post($post);
  1873. if ( empty($post) )
  1874. return;
  1875. $post_id = $post->ID;
  1876. $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
  1877. if ( empty($statuses) )
  1878. return true;
  1879. do_action('untrash_post_comments', $post_id);
  1880. // Restore each comment to its original status
  1881. $group_by_status = array();
  1882. foreach ( $statuses as $comment_id => $comment_status )
  1883. $group_by_status[$comment_status][] = $comment_id;
  1884. foreach ( $group_by_status as $status => $comments ) {
  1885. // Sanity check. This shouldn't happen.
  1886. if ( 'post-trashed' == $status )
  1887. $status = '0';
  1888. $comments_in = implode( "', '", $comments );
  1889. $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
  1890. }
  1891. clean_comment_cache( array_keys($statuses) );
  1892. delete_post_meta($post_id, '_wp_trash_meta_comments_status');
  1893. do_action('untrashed_post_comments', $post_id);
  1894. }
  1895. /**
  1896. * Retrieve the list of categories for a post.
  1897. *
  1898. * Compatibility layer for themes and plugins. Also an easy layer of abstraction
  1899. * away from the complexity of the taxonomy layer.
  1900. *
  1901. * @since 2.1.0
  1902. *
  1903. * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
  1904. *
  1905. * @param int $post_id Optional. The Post ID.
  1906. * @param array $args Optional. Overwrite the defaults.
  1907. * @return array
  1908. */
  1909. function wp_get_post_categories( $post_id = 0, $args = array() ) {
  1910. $post_id = (int) $post_id;
  1911. $defaults = array('fields' => 'ids');
  1912. $args = wp_parse_args( $args, $defaults );
  1913. $cats = wp_get_object_terms($post_id, 'category', $args);
  1914. return $cats;
  1915. }
  1916. /**
  1917. * Retrieve the tags for a post.
  1918. *
  1919. * There is only one default for this function, called 'fields' and by default
  1920. * is set to 'all'. There are other defaults that can be overridden in
  1921. * {@link wp_get_object_terms()}.
  1922. *
  1923. * @package WordPress
  1924. * @subpackage Post
  1925. * @since 2.3.0
  1926. *
  1927. * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
  1928. *
  1929. * @param int $post_id Optional. The Post ID
  1930. * @param array $args Optional. Overwrite the defaults
  1931. * @return array List of post tags.
  1932. */
  1933. function wp_get_post_tags( $post_id = 0, $args = array() ) {
  1934. return wp_get_post_terms( $post_id, 'post_tag', $args);
  1935. }
  1936. /**
  1937. * Retrieve the terms for a post.
  1938. *
  1939. * There is only one default for this function, called 'fields' and by default
  1940. * is set to 'all'. There are other defaults that can be overridden in
  1941. * {@link wp_get_object_terms()}.
  1942. *
  1943. * @package WordPress
  1944. * @subpackage Post
  1945. * @since 2.8.0
  1946. *
  1947. * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
  1948. *
  1949. * @param int $post_id Optional. The Post ID
  1950. * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
  1951. * @param array $args Optional. Overwrite the defaults
  1952. * @return array List of post tags.
  1953. */
  1954. function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
  1955. $post_id = (int) $post_id;
  1956. $defaults = array('fields' => 'all');
  1957. $args = wp_parse_args( $args, $defaults );
  1958. $tags = wp_get_object_terms($post_id, $taxonomy, $args);
  1959. return $tags;
  1960. }
  1961. /**
  1962. * Retrieve number of recent posts.
  1963. *
  1964. * @since 1.0.0
  1965. * @uses wp_parse_args()
  1966. * @uses get_posts()
  1967. *
  1968. * @param string $deprecated Deprecated.
  1969. * @param array $args Optional. Overrides defaults.
  1970. * @param string $output Optional.
  1971. * @return unknown.
  1972. */
  1973. function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
  1974. if ( is_numeric( $args ) ) {
  1975. _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  1976. $args = array( 'numberposts' => absint( $args ) );
  1977. }
  1978. // Set default arguments
  1979. $defaults = array(
  1980. 'numberposts' => 10, 'offset' => 0,
  1981. 'category' => 0, 'orderby' => 'post_date',
  1982. 'order' => 'DESC', 'include' => '',
  1983. 'exclude' => '', 'meta_key' => '',
  1984. 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
  1985. 'suppress_filters' => true
  1986. );
  1987. $r = wp_parse_args( $args, $defaults );
  1988. $results = get_posts( $r );
  1989. // Backward compatibility. Prior to 3.1 expected posts to be returned in array
  1990. if ( ARRAY_A == $output ){
  1991. foreach( $results as $key => $result ) {
  1992. $results[$key] = get_object_vars( $result );
  1993. }
  1994. return $results ? $results : array();
  1995. }
  1996. return $results ? $results : false;
  1997. }
  1998. /**
  1999. * Retrieve a single post, based on post ID.
  2000. *
  2001. * Has categories in 'post_category' property or key. Has tags in 'tags_input'
  2002. * property or key.
  2003. *
  2004. * @since 1.0.0
  2005. *
  2006. * @param int $postid Post ID.
  2007. * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
  2008. * @return object|array Post object or array holding post contents and information
  2009. */
  2010. function wp_get_single_post($postid = 0, $mode = OBJECT) {
  2011. $postid = (int) $postid;
  2012. $post = get_post($postid, $mode);
  2013. if (
  2014. ( OBJECT == $mode && empty( $post->ID ) ) ||
  2015. ( OBJECT != $mode && empty( $post['ID'] ) )
  2016. )
  2017. return ( OBJECT == $mode ? null : array() );
  2018. // Set categories and tags
  2019. if ( $mode == OBJECT ) {
  2020. $post->post_category = array();
  2021. if ( is_object_in_taxonomy($post->post_type, 'category') )
  2022. $post->post_category = wp_get_post_categories($postid);
  2023. $post->tags_input = array();
  2024. if ( is_object_in_taxonomy($post->post_type, 'post_tag') )
  2025. $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
  2026. } else {
  2027. $post['post_category'] = array();
  2028. if ( is_object_in_taxonomy($post['post_type'], 'category') )
  2029. $post['post_category'] = wp_get_post_categories($postid);
  2030. $post['tags_input'] = array();
  2031. if ( is_object_in_taxonomy($post['post_type'], 'post_tag') )
  2032. $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
  2033. }
  2034. return $post;
  2035. }
  2036. /**
  2037. * Insert a post.
  2038. *
  2039. * If the $postarr parameter has 'ID' set to a value, then post will be updated.
  2040. *
  2041. * You can set the post date manually, but setting the values for 'post_date'
  2042. * and 'post_date_gmt' keys. You can close the comments or open the comments by
  2043. * setting the value for 'comment_status' key.
  2044. *
  2045. * The defaults for the parameter $postarr are:
  2046. * 'post_status' - Default is 'draft'.
  2047. * 'post_type' - Default is 'post'.
  2048. * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
  2049. * 'ping_status' - Default is the value in 'default_ping_status' option.
  2050. * Whether the attachment can accept pings.
  2051. * 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
  2052. * 'menu_order' - Default is 0. The order it is displayed.
  2053. * 'to_ping' - Whether to ping.
  2054. * 'pinged' - Default is empty string.
  2055. * 'post_password' - Default is empty string. The password to access the attachment.
  2056. * 'guid' - Global Unique ID for referencing the attachment.
  2057. * 'post_content_filtered' - Post content filtered.
  2058. * 'post_excerpt' - Post excerpt.
  2059. *
  2060. * @since 1.0.0
  2061. * @uses $wpdb
  2062. * @uses $wp_rewrite
  2063. * @uses $user_ID
  2064. * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
  2065. * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
  2066. * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
  2067. * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
  2068. * @uses wp_transition_post_status()
  2069. *
  2070. * @param array $postarr Elements that make up post to insert.
  2071. * @param bool $wp_error Optional. Allow return of WP_Error on failure.
  2072. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  2073. */
  2074. function wp_insert_post($postarr, $wp_error = false) {
  2075. global $wpdb, $wp_rewrite, $user_ID;
  2076. $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  2077. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  2078. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  2079. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
  2080. 'post_content' => '', 'post_title' => '');
  2081. $postarr = wp_parse_args($postarr, $defaults);
  2082. $postarr = sanitize_post($postarr, 'db');
  2083. // export array as variables
  2084. extract($postarr, EXTR_SKIP);
  2085. // Are we updating or creating?
  2086. $update = false;
  2087. if ( !empty($ID) ) {
  2088. $update = true;
  2089. $previous_status = get_post_field('post_status', $ID);
  2090. } else {
  2091. $previous_status = 'new';
  2092. }
  2093. if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
  2094. if ( $wp_error )
  2095. return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
  2096. else
  2097. return 0;
  2098. }
  2099. if ( empty($post_type) )
  2100. $post_type = 'post';
  2101. if ( empty($post_status) )
  2102. $post_status = 'draft';
  2103. if ( !empty($post_category) )
  2104. $post_category = array_filter($post_category); // Filter out empty terms
  2105. // Make sure we set a valid category.
  2106. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  2107. // 'post' requires at least one category.
  2108. if ( 'post' == $post_type && 'auto-draft' != $post_status )
  2109. $post_category = array( get_option('default_category') );
  2110. else
  2111. $post_category = array();
  2112. }
  2113. if ( empty($post_author) )
  2114. $post_author = $user_ID;
  2115. $post_ID = 0;
  2116. // Get the post ID and GUID
  2117. if ( $update ) {
  2118. $post_ID = (int) $ID;
  2119. $guid = get_post_field( 'guid', $post_ID );
  2120. $post_before = get_post($post_ID);
  2121. }
  2122. // Don't allow contributors to set to set the post slug for pending review posts
  2123. if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
  2124. $post_name = '';
  2125. // Create a valid post name. Drafts and pending posts are allowed to have an empty
  2126. // post name.
  2127. if ( empty($post_name) ) {
  2128. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2129. $post_name = sanitize_title($post_title);
  2130. else
  2131. $post_name = '';
  2132. } else {
  2133. $post_name = sanitize_title($post_name);
  2134. }
  2135. // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
  2136. if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
  2137. $post_date = current_time('mysql');
  2138. if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
  2139. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2140. $post_date_gmt = get_gmt_from_date($post_date);
  2141. else
  2142. $post_date_gmt = '0000-00-00 00:00:00';
  2143. }
  2144. if ( $update || '0000-00-00 00:00:00' == $post_date ) {
  2145. $post_modified = current_time( 'mysql' );
  2146. $post_modified_gmt = current_time( 'mysql', 1 );
  2147. } else {
  2148. $post_modified = $post_date;
  2149. $post_modified_gmt = $post_date_gmt;
  2150. }
  2151. if ( 'publish' == $post_status ) {
  2152. $now = gmdate('Y-m-d H:i:59');
  2153. if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
  2154. $post_status = 'future';
  2155. } elseif( 'future' == $post_status ) {
  2156. $now = gmdate('Y-m-d H:i:59');
  2157. if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
  2158. $post_status = 'publish';
  2159. }
  2160. if ( empty($comment_status) ) {
  2161. if ( $update )
  2162. $comment_status = 'closed';
  2163. else
  2164. $comment_status = get_option('default_comment_status');
  2165. }
  2166. if ( empty($ping_status) )
  2167. $ping_status = get_option('default_ping_status');
  2168. if ( isset($to_ping) )
  2169. $to_ping = preg_replace('|\s+|', "\n", $to_ping);
  2170. else
  2171. $to_ping = '';
  2172. if ( ! isset($pinged) )
  2173. $pinged = '';
  2174. if ( isset($post_parent) )
  2175. $post_parent = (int) $post_parent;
  2176. else
  2177. $post_parent = 0;
  2178. // Check the post_parent to see if it will cause a hierarchy loop
  2179. $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
  2180. if ( isset($menu_order) )
  2181. $menu_order = (int) $menu_order;
  2182. else
  2183. $menu_order = 0;
  2184. if ( !isset($post_password) || 'private' == $post_status )
  2185. $post_password = '';
  2186. $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
  2187. // expected_slashed (everything!)
  2188. $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
  2189. $data = apply_filters('wp_insert_post_data', $data, $postarr);
  2190. $data = stripslashes_deep( $data );
  2191. $where = array( 'ID' => $post_ID );
  2192. if ( $update ) {
  2193. do_action( 'pre_post_update', $post_ID );
  2194. if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  2195. if ( $wp_error )
  2196. return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  2197. else
  2198. return 0;
  2199. }
  2200. } else {
  2201. if ( isset($post_mime_type) )
  2202. $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
  2203. // If there is a suggested ID, use it if not already present
  2204. if ( !empty($import_id) ) {
  2205. $import_id = (int) $import_id;
  2206. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  2207. $data['ID'] = $import_id;
  2208. }
  2209. }
  2210. if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
  2211. if ( $wp_error )
  2212. return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
  2213. else
  2214. return 0;
  2215. }
  2216. $post_ID = (int) $wpdb->insert_id;
  2217. // use the newly generated $post_ID
  2218. $where = array( 'ID' => $post_ID );
  2219. }
  2220. if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
  2221. $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
  2222. $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  2223. }
  2224. if ( is_object_in_taxonomy($post_type, 'category') )
  2225. wp_set_post_categories( $post_ID, $post_category );
  2226. if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
  2227. wp_set_post_tags( $post_ID, $tags_input );
  2228. // new-style support for all custom taxonomies
  2229. if ( !empty($tax_input) ) {
  2230. foreach ( $tax_input as $taxonomy => $tags ) {
  2231. $taxonomy_obj = get_taxonomy($taxonomy);
  2232. if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
  2233. $tags = array_filter($tags);
  2234. if ( current_user_can($taxonomy_obj->cap->assign_terms) )
  2235. wp_set_post_terms( $post_ID, $tags, $taxonomy );
  2236. }
  2237. }
  2238. $current_guid = get_post_field( 'guid', $post_ID );
  2239. if ( 'page' == $data['post_type'] )
  2240. clean_page_cache($post_ID);
  2241. else
  2242. clean_post_cache($post_ID);
  2243. // Set GUID
  2244. if ( !$update && '' == $current_guid )
  2245. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  2246. $post = get_post($post_ID);
  2247. if ( !empty($page_template) && 'page' == $data['post_type'] ) {
  2248. $post->page_template = $page_template;
  2249. $page_templates = get_page_templates();
  2250. if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
  2251. if ( $wp_error )
  2252. return new WP_Error('invalid_page_template', __('The page template is invalid.'));
  2253. else
  2254. return 0;
  2255. }
  2256. update_post_meta($post_ID, '_wp_page_template', $page_template);
  2257. }
  2258. wp_transition_post_status($data['post_status'], $previous_status, $post);
  2259. if ( $update ) {
  2260. do_action('edit_post', $post_ID, $post);
  2261. $post_after = get_post($post_ID);
  2262. do_action( 'post_updated', $post_ID, $post_after, $post_before);
  2263. }
  2264. do_action('save_post', $post_ID, $post);
  2265. do_action('wp_insert_post', $post_ID, $post);
  2266. return $post_ID;
  2267. }
  2268. /**
  2269. * Update a post with new post data.
  2270. *
  2271. * The date does not have to be set for drafts. You can set the date and it will
  2272. * not be overridden.
  2273. *
  2274. * @since 1.0.0
  2275. *
  2276. * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
  2277. * @return int 0 on failure, Post ID on success.
  2278. */
  2279. function wp_update_post($postarr = array()) {
  2280. if ( is_object($postarr) ) {
  2281. // non-escaped post was passed
  2282. $postarr = get_object_vars($postarr);
  2283. $postarr = add_magic_quotes($postarr);
  2284. }
  2285. // First, get all of the original fields
  2286. $post = wp_get_single_post($postarr['ID'], ARRAY_A);
  2287. // Escape data pulled from DB.
  2288. $post = add_magic_quotes($post);
  2289. // Passed post category list overwrites existing category list if not empty.
  2290. if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
  2291. && 0 != count($postarr['post_category']) )
  2292. $post_cats = $postarr['post_category'];
  2293. else
  2294. $post_cats = $post['post_category'];
  2295. // Drafts shouldn't be assigned a date unless explicitly done so by the user
  2296. if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
  2297. ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  2298. $clear_date = true;
  2299. else
  2300. $clear_date = false;
  2301. // Merge old and new fields with new fields overwriting old ones.
  2302. $postarr = array_merge($post, $postarr);
  2303. $postarr['post_category'] = $post_cats;
  2304. if ( $clear_date ) {
  2305. $postarr['post_date'] = current_time('mysql');
  2306. $postarr['post_date_gmt'] = '';
  2307. }
  2308. if ($postarr['post_type'] == 'attachment')
  2309. return wp_insert_attachment($postarr);
  2310. return wp_insert_post($postarr);
  2311. }
  2312. /**
  2313. * Publish a post by transitioning the post status.
  2314. *
  2315. * @since 2.1.0
  2316. * @uses $wpdb
  2317. * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
  2318. *
  2319. * @param int $post_id Post ID.
  2320. * @return null
  2321. */
  2322. function wp_publish_post($post_id) {
  2323. global $wpdb;
  2324. $post = get_post($post_id);
  2325. if ( empty($post) )
  2326. return;
  2327. if ( 'publish' == $post->post_status )
  2328. return;
  2329. $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
  2330. $old_status = $post->post_status;
  2331. $post->post_status = 'publish';
  2332. wp_transition_post_status('publish', $old_status, $post);
  2333. // Update counts for the post's terms.
  2334. foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
  2335. $tt_ids = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'tt_ids'));
  2336. wp_update_term_count($tt_ids, $taxonomy);
  2337. }
  2338. do_action('edit_post', $post_id, $post);
  2339. do_action('save_post', $post_id, $post);
  2340. do_action('wp_insert_post', $post_id, $post);
  2341. }
  2342. /**
  2343. * Publish future post and make sure post ID has future post status.
  2344. *
  2345. * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
  2346. * from publishing drafts, etc.
  2347. *
  2348. * @since 2.5.0
  2349. *
  2350. * @param int $post_id Post ID.
  2351. * @return null Nothing is returned. Which can mean that no action is required or post was published.
  2352. */
  2353. function check_and_publish_future_post($post_id) {
  2354. $post = get_post($post_id);
  2355. if ( empty($post) )
  2356. return;
  2357. if ( 'future' != $post->post_status )
  2358. return;
  2359. $time = strtotime( $post->post_date_gmt . ' GMT' );
  2360. if ( $time > time() ) { // Uh oh, someone jumped the gun!
  2361. wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
  2362. wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  2363. return;
  2364. }
  2365. return wp_publish_post($post_id);
  2366. }
  2367. /**
  2368. * Computes a unique slug for the post, when given the desired slug and some post details.
  2369. *
  2370. * @since 2.8.0
  2371. *
  2372. * @global wpdb $wpdb
  2373. * @global WP_Rewrite $wp_rewrite
  2374. * @param string $slug the desired slug (post_name)
  2375. * @param integer $post_ID
  2376. * @param string $post_status no uniqueness checks are made if the post is still draft or pending
  2377. * @param string $post_type
  2378. * @param integer $post_parent
  2379. * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  2380. */
  2381. function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
  2382. if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2383. return $slug;
  2384. global $wpdb, $wp_rewrite;
  2385. $feeds = $wp_rewrite->feeds;
  2386. if ( ! is_array( $feeds ) )
  2387. $feeds = array();
  2388. $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
  2389. if ( 'attachment' == $post_type ) {
  2390. // Attachment slugs must be unique across all types.
  2391. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  2392. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
  2393. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
  2394. $suffix = 2;
  2395. do {
  2396. $alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2397. $post_name_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_post_name, $post_ID ) );
  2398. $suffix++;
  2399. } while ( $post_name_check );
  2400. $slug = $alt_post_name;
  2401. }
  2402. } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
  2403. // Page slugs must be unique within their own trees. Pages are in a separate
  2404. // namespace than posts so page slugs are allowed to overlap post slugs.
  2405. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
  2406. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
  2407. if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
  2408. $suffix = 2;
  2409. do {
  2410. $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2411. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
  2412. $suffix++;
  2413. } while ( $post_name_check );
  2414. $slug = $alt_post_name;
  2415. }
  2416. } else {
  2417. // Post slugs must be unique across all posts.
  2418. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  2419. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
  2420. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
  2421. $suffix = 2;
  2422. do {
  2423. $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2424. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
  2425. $suffix++;
  2426. } while ( $post_name_check );
  2427. $slug = $alt_post_name;
  2428. }
  2429. }
  2430. return $slug;
  2431. }
  2432. /**
  2433. * Adds tags to a post.
  2434. *
  2435. * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
  2436. *
  2437. * @package WordPress
  2438. * @subpackage Post
  2439. * @since 2.3.0
  2440. *
  2441. * @param int $post_id Post ID
  2442. * @param string $tags The tags to set for the post, separated by commas.
  2443. * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
  2444. */
  2445. function wp_add_post_tags($post_id = 0, $tags = '') {
  2446. return wp_set_post_tags($post_id, $tags, true);
  2447. }
  2448. /**
  2449. * Set the tags for a post.
  2450. *
  2451. * @since 2.3.0
  2452. * @uses wp_set_object_terms() Sets the tags for the post.
  2453. *
  2454. * @param int $post_id Post ID.
  2455. * @param string $tags The tags to set for the post, separated by commas.
  2456. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2457. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2458. */
  2459. function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  2460. return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
  2461. }
  2462. /**
  2463. * Set the terms for a post.
  2464. *
  2465. * @since 2.8.0
  2466. * @uses wp_set_object_terms() Sets the tags for the post.
  2467. *
  2468. * @param int $post_id Post ID.
  2469. * @param string $tags The tags to set for the post, separated by commas.
  2470. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2471. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2472. */
  2473. function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  2474. $post_id = (int) $post_id;
  2475. if ( !$post_id )
  2476. return false;
  2477. if ( empty($tags) )
  2478. $tags = array();
  2479. $tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
  2480. // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
  2481. // names but different parents aren't confused.
  2482. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  2483. $tags = array_map( 'intval', $tags );
  2484. $tags = array_unique( $tags );
  2485. }
  2486. return wp_set_object_terms($post_id, $tags, $taxonomy, $append);
  2487. }
  2488. /**
  2489. * Set categories for a post.
  2490. *
  2491. * If the post categories parameter is not set, then the default category is
  2492. * going used.
  2493. *
  2494. * @since 2.1.0
  2495. *
  2496. * @param int $post_ID Post ID.
  2497. * @param array $post_categories Optional. List of categories.
  2498. * @return bool|mixed
  2499. */
  2500. function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
  2501. $post_ID = (int) $post_ID;
  2502. $post_type = get_post_type( $post_ID );
  2503. $post_status = get_post_status( $post_ID );
  2504. // If $post_categories isn't already an array, make it one:
  2505. if ( !is_array($post_categories) || empty($post_categories) ) {
  2506. if ( 'post' == $post_type && 'auto-draft' != $post_status )
  2507. $post_categories = array( get_option('default_category') );
  2508. else
  2509. $post_categories = array();
  2510. } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
  2511. return true;
  2512. }
  2513. if ( !empty($post_categories) ) {
  2514. $post_categories = array_map('intval', $post_categories);
  2515. $post_categories = array_unique($post_categories);
  2516. }
  2517. return wp_set_object_terms($post_ID, $post_categories, 'category');
  2518. }
  2519. /**
  2520. * Transition the post status of a post.
  2521. *
  2522. * Calls hooks to transition post status.
  2523. *
  2524. * The first is 'transition_post_status' with new status, old status, and post data.
  2525. *
  2526. * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
  2527. * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
  2528. * post data.
  2529. *
  2530. * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
  2531. * parameter and POSTTYPE is post_type post data.
  2532. *
  2533. * @since 2.3.0
  2534. * @link http://codex.wordpress.org/Post_Status_Transitions
  2535. *
  2536. * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
  2537. * $post if there is a status change.
  2538. * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
  2539. * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
  2540. *
  2541. * @param string $new_status Transition to this post status.
  2542. * @param string $old_status Previous post status.
  2543. * @param object $post Post data.
  2544. */
  2545. function wp_transition_post_status($new_status, $old_status, $post) {
  2546. do_action('transition_post_status', $new_status, $old_status, $post);
  2547. do_action("{$old_status}_to_{$new_status}", $post);
  2548. do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
  2549. }
  2550. //
  2551. // Trackback and ping functions
  2552. //
  2553. /**
  2554. * Add a URL to those already pung.
  2555. *
  2556. * @since 1.5.0
  2557. * @uses $wpdb
  2558. *
  2559. * @param int $post_id Post ID.
  2560. * @param string $uri Ping URI.
  2561. * @return int How many rows were updated.
  2562. */
  2563. function add_ping($post_id, $uri) {
  2564. global $wpdb;
  2565. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2566. $pung = trim($pung);
  2567. $pung = preg_split('/\s/', $pung);
  2568. $pung[] = $uri;
  2569. $new = implode("\n", $pung);
  2570. $new = apply_filters('add_ping', $new);
  2571. // expected_slashed ($new)
  2572. $new = stripslashes($new);
  2573. return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
  2574. }
  2575. /**
  2576. * Retrieve enclosures already enclosed for a post.
  2577. *
  2578. * @since 1.5.0
  2579. * @uses $wpdb
  2580. *
  2581. * @param int $post_id Post ID.
  2582. * @return array List of enclosures
  2583. */
  2584. function get_enclosed($post_id) {
  2585. $custom_fields = get_post_custom( $post_id );
  2586. $pung = array();
  2587. if ( !is_array( $custom_fields ) )
  2588. return $pung;
  2589. foreach ( $custom_fields as $key => $val ) {
  2590. if ( 'enclosure' != $key || !is_array( $val ) )
  2591. continue;
  2592. foreach( $val as $enc ) {
  2593. $enclosure = split( "\n", $enc );
  2594. $pung[] = trim( $enclosure[ 0 ] );
  2595. }
  2596. }
  2597. $pung = apply_filters('get_enclosed', $pung, $post_id);
  2598. return $pung;
  2599. }
  2600. /**
  2601. * Retrieve URLs already pinged for a post.
  2602. *
  2603. * @since 1.5.0
  2604. * @uses $wpdb
  2605. *
  2606. * @param int $post_id Post ID.
  2607. * @return array
  2608. */
  2609. function get_pung($post_id) {
  2610. global $wpdb;
  2611. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2612. $pung = trim($pung);
  2613. $pung = preg_split('/\s/', $pung);
  2614. $pung = apply_filters('get_pung', $pung);
  2615. return $pung;
  2616. }
  2617. /**
  2618. * Retrieve URLs that need to be pinged.
  2619. *
  2620. * @since 1.5.0
  2621. * @uses $wpdb
  2622. *
  2623. * @param int $post_id Post ID
  2624. * @return array
  2625. */
  2626. function get_to_ping($post_id) {
  2627. global $wpdb;
  2628. $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2629. $to_ping = trim($to_ping);
  2630. $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
  2631. $to_ping = apply_filters('get_to_ping', $to_ping);
  2632. return $to_ping;
  2633. }
  2634. /**
  2635. * Do trackbacks for a list of URLs.
  2636. *
  2637. * @since 1.0.0
  2638. *
  2639. * @param string $tb_list Comma separated list of URLs
  2640. * @param int $post_id Post ID
  2641. */
  2642. function trackback_url_list($tb_list, $post_id) {
  2643. if ( ! empty( $tb_list ) ) {
  2644. // get post data
  2645. $postdata = wp_get_single_post($post_id, ARRAY_A);
  2646. // import postdata as variables
  2647. extract($postdata, EXTR_SKIP);
  2648. // form an excerpt
  2649. $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
  2650. if (strlen($excerpt) > 255) {
  2651. $excerpt = substr($excerpt,0,252) . '...';
  2652. }
  2653. $trackback_urls = explode(',', $tb_list);
  2654. foreach( (array) $trackback_urls as $tb_url) {
  2655. $tb_url = trim($tb_url);
  2656. trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
  2657. }
  2658. }
  2659. }
  2660. //
  2661. // Page functions
  2662. //
  2663. /**
  2664. * Get a list of page IDs.
  2665. *
  2666. * @since 2.0.0
  2667. * @uses $wpdb
  2668. *
  2669. * @return array List of page IDs.
  2670. */
  2671. function get_all_page_ids() {
  2672. global $wpdb;
  2673. if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
  2674. $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
  2675. wp_cache_add('all_page_ids', $page_ids, 'posts');
  2676. }
  2677. return $page_ids;
  2678. }
  2679. /**
  2680. * Retrieves page data given a page ID or page object.
  2681. *
  2682. * @since 1.5.1
  2683. *
  2684. * @param mixed $page Page object or page ID. Passed by reference.
  2685. * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
  2686. * @param string $filter How the return value should be filtered.
  2687. * @return mixed Page data.
  2688. */
  2689. function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
  2690. $p = get_post($page, $output, $filter);
  2691. return $p;
  2692. }
  2693. /**
  2694. * Retrieves a page given its path.
  2695. *
  2696. * @since 2.1.0
  2697. * @uses $wpdb
  2698. *
  2699. * @param string $page_path Page path
  2700. * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
  2701. * @param string $post_type Optional. Post type. Default page.
  2702. * @return mixed Null when complete.
  2703. */
  2704. function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
  2705. global $wpdb;
  2706. $null = null;
  2707. $page_path = rawurlencode(urldecode($page_path));
  2708. $page_path = str_replace('%2F', '/', $page_path);
  2709. $page_path = str_replace('%20', ' ', $page_path);
  2710. $page_paths = '/' . trim($page_path, '/');
  2711. $leaf_path = sanitize_title(basename($page_paths));
  2712. $page_paths = explode('/', $page_paths);
  2713. $full_path = '';
  2714. foreach ( (array) $page_paths as $pathdir )
  2715. $full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title($pathdir);
  2716. $pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = %s OR post_type = 'attachment')", $leaf_path, $post_type ));
  2717. if ( empty($pages) )
  2718. return $null;
  2719. foreach ( $pages as $page ) {
  2720. $path = '/' . $leaf_path;
  2721. $curpage = $page;
  2722. while ( $curpage->post_parent != 0 ) {
  2723. $post_parent = $curpage->post_parent;
  2724. $curpage = wp_cache_get( $post_parent, 'posts' );
  2725. if ( false === $curpage )
  2726. $curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type = %s", $post_parent, $post_type ) );
  2727. $path = '/' . $curpage->post_name . $path;
  2728. }
  2729. if ( $path == $full_path )
  2730. return get_page($page->ID, $output, $post_type);
  2731. }
  2732. return $null;
  2733. }
  2734. /**
  2735. * Retrieve a page given its title.
  2736. *
  2737. * @since 2.1.0
  2738. * @uses $wpdb
  2739. *
  2740. * @param string $page_title Page title
  2741. * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
  2742. * @param string $post_type Optional. Post type. Default page.
  2743. * @return mixed
  2744. */
  2745. function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
  2746. global $wpdb;
  2747. $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
  2748. if ( $page )
  2749. return get_page($page, $output);
  2750. return null;
  2751. }
  2752. /**
  2753. * Retrieve child pages from list of pages matching page ID.
  2754. *
  2755. * Matches against the pages parameter against the page ID. Also matches all
  2756. * children for the same to retrieve all children of a page. Does not make any
  2757. * SQL queries to get the children.
  2758. *
  2759. * @since 1.5.1
  2760. *
  2761. * @param int $page_id Page ID.
  2762. * @param array $pages List of pages' objects.
  2763. * @return array
  2764. */
  2765. function &get_page_children($page_id, $pages) {
  2766. $page_list = array();
  2767. foreach ( (array) $pages as $page ) {
  2768. if ( $page->post_parent == $page_id ) {
  2769. $page_list[] = $page;
  2770. if ( $children = get_page_children($page->ID, $pages) )
  2771. $page_list = array_merge($page_list, $children);
  2772. }
  2773. }
  2774. return $page_list;
  2775. }
  2776. /**
  2777. * Order the pages with children under parents in a flat list.
  2778. *
  2779. * It uses auxiliary structure to hold parent-children relationships and
  2780. * runs in O(N) complexity
  2781. *
  2782. * @since 2.0.0
  2783. *
  2784. * @param array $pages Posts array.
  2785. * @param int $page_id Parent page ID.
  2786. * @return array A list arranged by hierarchy. Children immediately follow their parents.
  2787. */
  2788. function &get_page_hierarchy( &$pages, $page_id = 0 ) {
  2789. if ( empty( $pages ) ) {
  2790. $result = array();
  2791. return $result;
  2792. }
  2793. $children = array();
  2794. foreach ( (array) $pages as $p ) {
  2795. $parent_id = intval( $p->post_parent );
  2796. $children[ $parent_id ][] = $p;
  2797. }
  2798. $result = array();
  2799. _page_traverse_name( $page_id, $children, $result );
  2800. return $result;
  2801. }
  2802. /**
  2803. * function to traverse and return all the nested children post names of a root page.
  2804. * $children contains parent-chilren relations
  2805. *
  2806. * @since 2.9.0
  2807. */
  2808. function _page_traverse_name( $page_id, &$children, &$result ){
  2809. if ( isset( $children[ $page_id ] ) ){
  2810. foreach( (array)$children[ $page_id ] as $child ) {
  2811. $result[ $child->ID ] = $child->post_name;
  2812. _page_traverse_name( $child->ID, $children, $result );
  2813. }
  2814. }
  2815. }
  2816. /**
  2817. * Builds URI for a page.
  2818. *
  2819. * Sub pages will be in the "directory" under the parent page post name.
  2820. *
  2821. * @since 1.5.0
  2822. *
  2823. * @param mixed $page Page object or page ID.
  2824. * @return string Page URI.
  2825. */
  2826. function get_page_uri($page) {
  2827. if ( ! is_object($page) )
  2828. $page = get_page($page);
  2829. $uri = $page->post_name;
  2830. // A page cannot be it's own parent.
  2831. if ( $page->post_parent == $page->ID )
  2832. return $uri;
  2833. while ($page->post_parent != 0) {
  2834. $page = get_page($page->post_parent);
  2835. $uri = $page->post_name . "/" . $uri;
  2836. }
  2837. return $uri;
  2838. }
  2839. /**
  2840. * Retrieve a list of pages.
  2841. *
  2842. * The defaults that can be overridden are the following: 'child_of',
  2843. * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
  2844. * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
  2845. *
  2846. * @since 1.5.0
  2847. * @uses $wpdb
  2848. *
  2849. * @param mixed $args Optional. Array or string of options that overrides defaults.
  2850. * @return array List of pages matching defaults or $args
  2851. */
  2852. function &get_pages($args = '') {
  2853. global $wpdb;
  2854. $defaults = array(
  2855. 'child_of' => 0, 'sort_order' => 'ASC',
  2856. 'sort_column' => 'post_title', 'hierarchical' => 1,
  2857. 'exclude' => array(), 'include' => array(),
  2858. 'meta_key' => '', 'meta_value' => '',
  2859. 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
  2860. 'number' => '', 'offset' => 0,
  2861. 'post_type' => 'page', 'post_status' => 'publish',
  2862. );
  2863. $r = wp_parse_args( $args, $defaults );
  2864. extract( $r, EXTR_SKIP );
  2865. $number = (int) $number;
  2866. $offset = (int) $offset;
  2867. // Make sure the post type is hierarchical
  2868. $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
  2869. if ( !in_array( $post_type, $hierarchical_post_types ) )
  2870. return false;
  2871. // Make sure we have a valid post status
  2872. if ( !in_array($post_status, get_post_stati()) )
  2873. return false;
  2874. $cache = array();
  2875. $key = md5( serialize( compact(array_keys($defaults)) ) );
  2876. if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
  2877. if ( is_array($cache) && isset( $cache[ $key ] ) ) {
  2878. $pages = apply_filters('get_pages', $cache[ $key ], $r );
  2879. return $pages;
  2880. }
  2881. }
  2882. if ( !is_array($cache) )
  2883. $cache = array();
  2884. $inclusions = '';
  2885. if ( !empty($include) ) {
  2886. $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
  2887. $parent = -1;
  2888. $exclude = '';
  2889. $meta_key = '';
  2890. $meta_value = '';
  2891. $hierarchical = false;
  2892. $incpages = wp_parse_id_list( $include );
  2893. if ( ! empty( $incpages ) ) {
  2894. foreach ( $incpages as $incpage ) {
  2895. if (empty($inclusions))
  2896. $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
  2897. else
  2898. $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
  2899. }
  2900. }
  2901. }
  2902. if (!empty($inclusions))
  2903. $inclusions .= ')';
  2904. $exclusions = '';
  2905. if ( !empty($exclude) ) {
  2906. $expages = wp_parse_id_list( $exclude );
  2907. if ( ! empty( $expages ) ) {
  2908. foreach ( $expages as $expage ) {
  2909. if (empty($exclusions))
  2910. $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
  2911. else
  2912. $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
  2913. }
  2914. }
  2915. }
  2916. if (!empty($exclusions))
  2917. $exclusions .= ')';
  2918. $author_query = '';
  2919. if (!empty($authors)) {
  2920. $post_authors = preg_split('/[\s,]+/',$authors);
  2921. if ( ! empty( $post_authors ) ) {
  2922. foreach ( $post_authors as $post_author ) {
  2923. //Do we have an author id or an author login?
  2924. if ( 0 == intval($post_author) ) {
  2925. $post_author = get_userdatabylogin($post_author);
  2926. if ( empty($post_author) )
  2927. continue;
  2928. if ( empty($post_author->ID) )
  2929. continue;
  2930. $post_author = $post_author->ID;
  2931. }
  2932. if ( '' == $author_query )
  2933. $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
  2934. else
  2935. $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
  2936. }
  2937. if ( '' != $author_query )
  2938. $author_query = " AND ($author_query)";
  2939. }
  2940. }
  2941. $join = '';
  2942. $where = "$exclusions $inclusions ";
  2943. if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
  2944. $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
  2945. // meta_key and meta_value might be slashed
  2946. $meta_key = stripslashes($meta_key);
  2947. $meta_value = stripslashes($meta_value);
  2948. if ( ! empty( $meta_key ) )
  2949. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
  2950. if ( ! empty( $meta_value ) )
  2951. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
  2952. }
  2953. if ( $parent >= 0 )
  2954. $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
  2955. $where_post_type = $wpdb->prepare( "post_type = '%s' AND post_status = '%s'", $post_type, $post_status );
  2956. $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
  2957. $query .= $author_query;
  2958. $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
  2959. if ( !empty($number) )
  2960. $query .= ' LIMIT ' . $offset . ',' . $number;
  2961. $pages = $wpdb->get_results($query);
  2962. if ( empty($pages) ) {
  2963. $pages = apply_filters('get_pages', array(), $r);
  2964. return $pages;
  2965. }
  2966. // Sanitize before caching so it'll only get done once
  2967. $num_pages = count($pages);
  2968. for ($i = 0; $i < $num_pages; $i++) {
  2969. $pages[$i] = sanitize_post($pages[$i], 'raw');
  2970. }
  2971. // Update cache.
  2972. update_page_cache($pages);
  2973. if ( $child_of || $hierarchical )
  2974. $pages = & get_page_children($child_of, $pages);
  2975. if ( !empty($exclude_tree) ) {
  2976. $exclude = (int) $exclude_tree;
  2977. $children = get_page_children($exclude, $pages);
  2978. $excludes = array();
  2979. foreach ( $children as $child )
  2980. $excludes[] = $child->ID;
  2981. $excludes[] = $exclude;
  2982. $num_pages = count($pages);
  2983. for ( $i = 0; $i < $num_pages; $i++ ) {
  2984. if ( in_array($pages[$i]->ID, $excludes) )
  2985. unset($pages[$i]);
  2986. }
  2987. }
  2988. $cache[ $key ] = $pages;
  2989. wp_cache_set( 'get_pages', $cache, 'posts' );
  2990. $pages = apply_filters('get_pages', $pages, $r);
  2991. return $pages;
  2992. }
  2993. //
  2994. // Attachment functions
  2995. //
  2996. /**
  2997. * Check if the attachment URI is local one and is really an attachment.
  2998. *
  2999. * @since 2.0.0
  3000. *
  3001. * @param string $url URL to check
  3002. * @return bool True on success, false on failure.
  3003. */
  3004. function is_local_attachment($url) {
  3005. if (strpos($url, home_url()) === false)
  3006. return false;
  3007. if (strpos($url, home_url('/?attachment_id=')) !== false)
  3008. return true;
  3009. if ( $id = url_to_postid($url) ) {
  3010. $post = & get_post($id);
  3011. if ( 'attachment' == $post->post_type )
  3012. return true;
  3013. }
  3014. return false;
  3015. }
  3016. /**
  3017. * Insert an attachment.
  3018. *
  3019. * If you set the 'ID' in the $object parameter, it will mean that you are
  3020. * updating and attempt to update the attachment. You can also set the
  3021. * attachment name or title by setting the key 'post_name' or 'post_title'.
  3022. *
  3023. * You can set the dates for the attachment manually by setting the 'post_date'
  3024. * and 'post_date_gmt' keys' values.
  3025. *
  3026. * By default, the comments will use the default settings for whether the
  3027. * comments are allowed. You can close them manually or keep them open by
  3028. * setting the value for the 'comment_status' key.
  3029. *
  3030. * The $object parameter can have the following:
  3031. * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
  3032. * 'post_type' - Default is 'post', will be set to attachment. Can not override.
  3033. * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
  3034. * 'ping_status' - Default is the value in default ping status option. Whether the attachment
  3035. * can accept pings.
  3036. * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
  3037. * to, if any.
  3038. * 'menu_order' - Default is 0. The order it is displayed.
  3039. * 'to_ping' - Whether to ping.
  3040. * 'pinged' - Default is empty string.
  3041. * 'post_password' - Default is empty string. The password to access the attachment.
  3042. * 'guid' - Global Unique ID for referencing the attachment.
  3043. * 'post_content_filtered' - Attachment post content filtered.
  3044. * 'post_excerpt' - Attachment excerpt.
  3045. *
  3046. * @since 2.0.0
  3047. * @uses $wpdb
  3048. * @uses $user_ID
  3049. * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
  3050. * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
  3051. *
  3052. * @param string|array $object Arguments to override defaults.
  3053. * @param string $file Optional filename.
  3054. * @param int $parent Parent post ID.
  3055. * @return int Attachment ID.
  3056. */
  3057. function wp_insert_attachment($object, $file = false, $parent = 0) {
  3058. global $wpdb, $user_ID;
  3059. $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  3060. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  3061. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  3062. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
  3063. $object = wp_parse_args($object, $defaults);
  3064. if ( !empty($parent) )
  3065. $object['post_parent'] = $parent;
  3066. $object = sanitize_post($object, 'db');
  3067. // export array as variables
  3068. extract($object, EXTR_SKIP);
  3069. if ( empty($post_author) )
  3070. $post_author = $user_ID;
  3071. $post_type = 'attachment';
  3072. $post_status = 'inherit';
  3073. // Make sure we set a valid category.
  3074. if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  3075. // 'post' requires at least one category.
  3076. if ( 'post' == $post_type )
  3077. $post_category = array( get_option('default_category') );
  3078. else
  3079. $post_category = array();
  3080. }
  3081. // Are we updating or creating?
  3082. if ( !empty($ID) ) {
  3083. $update = true;
  3084. $post_ID = (int) $ID;
  3085. } else {
  3086. $update = false;
  3087. $post_ID = 0;
  3088. }
  3089. // Create a valid post name.
  3090. if ( empty($post_name) )
  3091. $post_name = sanitize_title($post_title);
  3092. else
  3093. $post_name = sanitize_title($post_name);
  3094. // expected_slashed ($post_name)
  3095. $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
  3096. if ( empty($post_date) )
  3097. $post_date = current_time('mysql');
  3098. if ( empty($post_date_gmt) )
  3099. $post_date_gmt = current_time('mysql', 1);
  3100. if ( empty($post_modified) )
  3101. $post_modified = $post_date;
  3102. if ( empty($post_modified_gmt) )
  3103. $post_modified_gmt = $post_date_gmt;
  3104. if ( empty($comment_status) ) {
  3105. if ( $update )
  3106. $comment_status = 'closed';
  3107. else
  3108. $comment_status = get_option('default_comment_status');
  3109. }
  3110. if ( empty($ping_status) )
  3111. $ping_status = get_option('default_ping_status');
  3112. if ( isset($to_ping) )
  3113. $to_ping = preg_replace('|\s+|', "\n", $to_ping);
  3114. else
  3115. $to_ping = '';
  3116. if ( isset($post_parent) )
  3117. $post_parent = (int) $post_parent;
  3118. else
  3119. $post_parent = 0;
  3120. if ( isset($menu_order) )
  3121. $menu_order = (int) $menu_order;
  3122. else
  3123. $menu_order = 0;
  3124. if ( !isset($post_password) )
  3125. $post_password = '';
  3126. if ( ! isset($pinged) )
  3127. $pinged = '';
  3128. // expected_slashed (everything!)
  3129. $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) );
  3130. $data = stripslashes_deep( $data );
  3131. if ( $update ) {
  3132. $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
  3133. } else {
  3134. // If there is a suggested ID, use it if not already present
  3135. if ( !empty($import_id) ) {
  3136. $import_id = (int) $import_id;
  3137. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  3138. $data['ID'] = $import_id;
  3139. }
  3140. }
  3141. $wpdb->insert( $wpdb->posts, $data );
  3142. $post_ID = (int) $wpdb->insert_id;
  3143. }
  3144. if ( empty($post_name) ) {
  3145. $post_name = sanitize_title($post_title, $post_ID);
  3146. $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
  3147. }
  3148. wp_set_post_categories($post_ID, $post_category);
  3149. if ( $file )
  3150. update_attached_file( $post_ID, $file );
  3151. clean_post_cache($post_ID);
  3152. if ( isset($post_parent) && $post_parent < 0 )
  3153. add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
  3154. if ( $update) {
  3155. do_action('edit_attachment', $post_ID);
  3156. } else {
  3157. do_action('add_attachment', $post_ID);
  3158. }
  3159. return $post_ID;
  3160. }
  3161. /**
  3162. * Trashes or deletes an attachment.
  3163. *
  3164. * When an attachment is permanently deleted, the file will also be removed.
  3165. * Deletion removes all post meta fields, taxonomy, comments, etc. associated
  3166. * with the attachment (except the main post).
  3167. *
  3168. * The attachment is moved to the trash instead of permanently deleted unless trash
  3169. * for media is disabled, item is already in the trash, or $force_delete is true.
  3170. *
  3171. * @since 2.0.0
  3172. * @uses $wpdb
  3173. * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
  3174. *
  3175. * @param int $post_id Attachment ID.
  3176. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  3177. * @return mixed False on failure. Post data on success.
  3178. */
  3179. function wp_delete_attachment( $post_id, $force_delete = false ) {
  3180. global $wpdb;
  3181. if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
  3182. return $post;
  3183. if ( 'attachment' != $post->post_type )
  3184. return false;
  3185. if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
  3186. return wp_trash_post( $post_id );
  3187. delete_post_meta($post_id, '_wp_trash_meta_status');
  3188. delete_post_meta($post_id, '_wp_trash_meta_time');
  3189. $meta = wp_get_attachment_metadata( $post_id );
  3190. $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  3191. $file = get_attached_file( $post_id );
  3192. if ( is_multisite() )
  3193. delete_transient( 'dirsize_cache' );
  3194. do_action('delete_attachment', $post_id);
  3195. wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
  3196. wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
  3197. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND meta_value = %d", $post_id ));
  3198. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
  3199. if ( ! empty( $comment_ids ) ) {
  3200. do_action( 'delete_comment', $comment_ids );
  3201. foreach ( $comment_ids as $comment_id )
  3202. wp_delete_comment( $comment_id, true );
  3203. do_action( 'deleted_comment', $comment_ids );
  3204. }
  3205. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
  3206. if ( !empty($post_meta_ids) ) {
  3207. do_action( 'delete_postmeta', $post_meta_ids );
  3208. $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
  3209. $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
  3210. do_action( 'deleted_postmeta', $post_meta_ids );
  3211. }
  3212. do_action( 'delete_post', $post_id );
  3213. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3214. do_action( 'deleted_post', $post_id );
  3215. $uploadpath = wp_upload_dir();
  3216. if ( ! empty($meta['thumb']) ) {
  3217. // Don't delete the thumb if another attachment uses it
  3218. if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) {
  3219. $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
  3220. $thumbfile = apply_filters('wp_delete_file', $thumbfile);
  3221. @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
  3222. }
  3223. }
  3224. // remove intermediate and backup images if there are any
  3225. foreach ( get_intermediate_image_sizes() as $size ) {
  3226. if ( $intermediate = image_get_intermediate_size($post_id, $size) ) {
  3227. $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
  3228. @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
  3229. }
  3230. }
  3231. if ( is_array($backup_sizes) ) {
  3232. foreach ( $backup_sizes as $size ) {
  3233. $del_file = path_join( dirname($meta['file']), $size['file'] );
  3234. $del_file = apply_filters('wp_delete_file', $del_file);
  3235. @ unlink( path_join($uploadpath['basedir'], $del_file) );
  3236. }
  3237. }
  3238. $file = apply_filters('wp_delete_file', $file);
  3239. if ( ! empty($file) )
  3240. @ unlink($file);
  3241. clean_post_cache($post_id);
  3242. return $post;
  3243. }
  3244. /**
  3245. * Retrieve attachment meta field for attachment ID.
  3246. *
  3247. * @since 2.1.0
  3248. *
  3249. * @param int $post_id Attachment ID
  3250. * @param bool $unfiltered Optional, default is false. If true, filters are not run.
  3251. * @return string|bool Attachment meta field. False on failure.
  3252. */
  3253. function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
  3254. $post_id = (int) $post_id;
  3255. if ( !$post =& get_post( $post_id ) )
  3256. return false;
  3257. $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
  3258. if ( $unfiltered )
  3259. return $data;
  3260. return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
  3261. }
  3262. /**
  3263. * Update metadata for an attachment.
  3264. *
  3265. * @since 2.1.0
  3266. *
  3267. * @param int $post_id Attachment ID.
  3268. * @param array $data Attachment data.
  3269. * @return int
  3270. */
  3271. function wp_update_attachment_metadata( $post_id, $data ) {
  3272. $post_id = (int) $post_id;
  3273. if ( !$post =& get_post( $post_id ) )
  3274. return false;
  3275. $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
  3276. return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
  3277. }
  3278. /**
  3279. * Retrieve the URL for an attachment.
  3280. *
  3281. * @since 2.1.0
  3282. *
  3283. * @param int $post_id Attachment ID.
  3284. * @return string
  3285. */
  3286. function wp_get_attachment_url( $post_id = 0 ) {
  3287. $post_id = (int) $post_id;
  3288. if ( !$post =& get_post( $post_id ) )
  3289. return false;
  3290. $url = '';
  3291. if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
  3292. if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
  3293. if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
  3294. $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
  3295. elseif ( false !== strpos($file, 'wp-content/uploads') )
  3296. $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
  3297. else
  3298. $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
  3299. }
  3300. }
  3301. if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
  3302. $url = get_the_guid( $post->ID );
  3303. $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
  3304. if ( 'attachment' != $post->post_type || empty( $url ) )
  3305. return false;
  3306. return $url;
  3307. }
  3308. /**
  3309. * Retrieve thumbnail for an attachment.
  3310. *
  3311. * @since 2.1.0
  3312. *
  3313. * @param int $post_id Attachment ID.
  3314. * @return mixed False on failure. Thumbnail file path on success.
  3315. */
  3316. function wp_get_attachment_thumb_file( $post_id = 0 ) {
  3317. $post_id = (int) $post_id;
  3318. if ( !$post =& get_post( $post_id ) )
  3319. return false;
  3320. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
  3321. return false;
  3322. $file = get_attached_file( $post->ID );
  3323. if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
  3324. return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
  3325. return false;
  3326. }
  3327. /**
  3328. * Retrieve URL for an attachment thumbnail.
  3329. *
  3330. * @since 2.1.0
  3331. *
  3332. * @param int $post_id Attachment ID
  3333. * @return string|bool False on failure. Thumbnail URL on success.
  3334. */
  3335. function wp_get_attachment_thumb_url( $post_id = 0 ) {
  3336. $post_id = (int) $post_id;
  3337. if ( !$post =& get_post( $post_id ) )
  3338. return false;
  3339. if ( !$url = wp_get_attachment_url( $post->ID ) )
  3340. return false;
  3341. $sized = image_downsize( $post_id, 'thumbnail' );
  3342. if ( $sized )
  3343. return $sized[0];
  3344. if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
  3345. return false;
  3346. $url = str_replace(basename($url), basename($thumb), $url);
  3347. return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
  3348. }
  3349. /**
  3350. * Check if the attachment is an image.
  3351. *
  3352. * @since 2.1.0
  3353. *
  3354. * @param int $post_id Attachment ID
  3355. * @return bool
  3356. */
  3357. function wp_attachment_is_image( $post_id = 0 ) {
  3358. $post_id = (int) $post_id;
  3359. if ( !$post =& get_post( $post_id ) )
  3360. return false;
  3361. if ( !$file = get_attached_file( $post->ID ) )
  3362. return false;
  3363. $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
  3364. $image_exts = array('jpg', 'jpeg', 'gif', 'png');
  3365. if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
  3366. return true;
  3367. return false;
  3368. }
  3369. /**
  3370. * Retrieve the icon for a MIME type.
  3371. *
  3372. * @since 2.1.0
  3373. *
  3374. * @param string $mime MIME type
  3375. * @return string|bool
  3376. */
  3377. function wp_mime_type_icon( $mime = 0 ) {
  3378. if ( !is_numeric($mime) )
  3379. $icon = wp_cache_get("mime_type_icon_$mime");
  3380. if ( empty($icon) ) {
  3381. $post_id = 0;
  3382. $post_mimes = array();
  3383. if ( is_numeric($mime) ) {
  3384. $mime = (int) $mime;
  3385. if ( $post =& get_post( $mime ) ) {
  3386. $post_id = (int) $post->ID;
  3387. $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
  3388. if ( !empty($ext) ) {
  3389. $post_mimes[] = $ext;
  3390. if ( $ext_type = wp_ext2type( $ext ) )
  3391. $post_mimes[] = $ext_type;
  3392. }
  3393. $mime = $post->post_mime_type;
  3394. } else {
  3395. $mime = 0;
  3396. }
  3397. } else {
  3398. $post_mimes[] = $mime;
  3399. }
  3400. $icon_files = wp_cache_get('icon_files');
  3401. if ( !is_array($icon_files) ) {
  3402. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  3403. $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
  3404. $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
  3405. $icon_files = array();
  3406. while ( $dirs ) {
  3407. $dir = array_shift($keys = array_keys($dirs));
  3408. $uri = array_shift($dirs);
  3409. if ( $dh = opendir($dir) ) {
  3410. while ( false !== $file = readdir($dh) ) {
  3411. $file = basename($file);
  3412. if ( substr($file, 0, 1) == '.' )
  3413. continue;
  3414. if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
  3415. if ( is_dir("$dir/$file") )
  3416. $dirs["$dir/$file"] = "$uri/$file";
  3417. continue;
  3418. }
  3419. $icon_files["$dir/$file"] = "$uri/$file";
  3420. }
  3421. closedir($dh);
  3422. }
  3423. }
  3424. wp_cache_set('icon_files', $icon_files, 600);
  3425. }
  3426. // Icon basename - extension = MIME wildcard
  3427. foreach ( $icon_files as $file => $uri )
  3428. $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
  3429. if ( ! empty($mime) ) {
  3430. $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
  3431. $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
  3432. $post_mimes[] = str_replace('/', '_', $mime);
  3433. }
  3434. $matches = wp_match_mime_types(array_keys($types), $post_mimes);
  3435. $matches['default'] = array('default');
  3436. foreach ( $matches as $match => $wilds ) {
  3437. if ( isset($types[$wilds[0]])) {
  3438. $icon = $types[$wilds[0]];
  3439. if ( !is_numeric($mime) )
  3440. wp_cache_set("mime_type_icon_$mime", $icon);
  3441. break;
  3442. }
  3443. }
  3444. }
  3445. return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
  3446. }
  3447. /**
  3448. * Checked for changed slugs for published post objects and save the old slug.
  3449. *
  3450. * The function is used when a post object of any type is updated,
  3451. * by comparing the current and previous post objects.
  3452. *
  3453. * If the slug was changed and not already part of the old slugs then it will be
  3454. * added to the post meta field ('_wp_old_slug') for storing old slugs for that
  3455. * post.
  3456. *
  3457. * The most logically usage of this function is redirecting changed post objects, so
  3458. * that those that linked to an changed post will be redirected to the new post.
  3459. *
  3460. * @since 2.1.0
  3461. *
  3462. * @param int $post_id Post ID.
  3463. * @param object $post The Post Object
  3464. * @param object $post_before The Previous Post Object
  3465. * @return int Same as $post_id
  3466. */
  3467. function wp_check_for_changed_slugs($post_id, $post, $post_before) {
  3468. // dont bother if it hasnt changed
  3469. if ( $post->post_name == $post_before->post_name )
  3470. return;
  3471. // we're only concerned with published, non-hierarchical objects
  3472. if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
  3473. return;
  3474. $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
  3475. // if we haven't added this old slug before, add it now
  3476. if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
  3477. add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
  3478. // if the new slug was used previously, delete it from the list
  3479. if ( in_array($post->post_name, $old_slugs) )
  3480. delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
  3481. }
  3482. /**
  3483. * Retrieve the private post SQL based on capability.
  3484. *
  3485. * This function provides a standardized way to appropriately select on the
  3486. * post_status of posts/pages. The function will return a piece of SQL code that
  3487. * can be added to a WHERE clause; this SQL is constructed to allow all
  3488. * published posts, and all private posts to which the user has access.
  3489. *
  3490. * It also allows plugins that define their own post type to control the cap by
  3491. * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
  3492. * the capability the user must have to read the private post type.
  3493. *
  3494. * @since 2.2.0
  3495. *
  3496. * @uses $user_ID
  3497. * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
  3498. *
  3499. * @param string $post_type currently only supports 'post' or 'page'.
  3500. * @return string SQL code that can be added to a where clause.
  3501. */
  3502. function get_private_posts_cap_sql($post_type) {
  3503. return get_posts_by_author_sql($post_type, FALSE);
  3504. }
  3505. /**
  3506. * Retrieve the post SQL based on capability, author, and type.
  3507. *
  3508. * See above for full description.
  3509. *
  3510. * @since 3.0.0
  3511. * @param string $post_type currently only supports 'post' or 'page'.
  3512. * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
  3513. * @param int $post_author Optional. Query posts having a single author ID.
  3514. * @return string SQL WHERE code that can be added to a query.
  3515. */
  3516. function get_posts_by_author_sql($post_type, $full = TRUE, $post_author = NULL) {
  3517. global $user_ID, $wpdb;
  3518. // Private posts
  3519. if ($post_type == 'post') {
  3520. $cap = 'read_private_posts';
  3521. // Private pages
  3522. } elseif ($post_type == 'page') {
  3523. $cap = 'read_private_pages';
  3524. // Dunno what it is, maybe plugins have their own post type?
  3525. } else {
  3526. $cap = '';
  3527. $cap = apply_filters('pub_priv_sql_capability', $cap);
  3528. if (empty($cap)) {
  3529. // We don't know what it is, filters don't change anything,
  3530. // so set the SQL up to return nothing.
  3531. return ' 1 = 0 ';
  3532. }
  3533. }
  3534. if ($full) {
  3535. if (is_null($post_author)) {
  3536. $sql = $wpdb->prepare('WHERE post_type = %s AND ', $post_type);
  3537. } else {
  3538. $sql = $wpdb->prepare('WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type);
  3539. }
  3540. } else {
  3541. $sql = '';
  3542. }
  3543. $sql .= "(post_status = 'publish'";
  3544. if (current_user_can($cap)) {
  3545. // Does the user have the capability to view private posts? Guess so.
  3546. $sql .= " OR post_status = 'private'";
  3547. } elseif (is_user_logged_in()) {
  3548. // Users can view their own private posts.
  3549. $id = (int) $user_ID;
  3550. if (is_null($post_author) || !$full) {
  3551. $sql .= " OR post_status = 'private' AND post_author = $id";
  3552. } elseif ($id == (int)$post_author) {
  3553. $sql .= " OR post_status = 'private'";
  3554. } // else none
  3555. } // else none
  3556. $sql .= ')';
  3557. return $sql;
  3558. }
  3559. /**
  3560. * Retrieve the date that the last post was published.
  3561. *
  3562. * The server timezone is the default and is the difference between GMT and
  3563. * server time. The 'blog' value is the date when the last post was posted. The
  3564. * 'gmt' is when the last post was posted in GMT formatted date.
  3565. *
  3566. * @since 0.71
  3567. *
  3568. * @uses apply_filters() Calls 'get_lastpostdate' filter
  3569. *
  3570. * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  3571. * @return string The date of the last post.
  3572. */
  3573. function get_lastpostdate($timezone = 'server') {
  3574. return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
  3575. }
  3576. /**
  3577. * Retrieve last post modified date depending on timezone.
  3578. *
  3579. * The server timezone is the default and is the difference between GMT and
  3580. * server time. The 'blog' value is just when the last post was modified. The
  3581. * 'gmt' is when the last post was modified in GMT time.
  3582. *
  3583. * @since 1.2.0
  3584. * @uses apply_filters() Calls 'get_lastpostmodified' filter
  3585. *
  3586. * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  3587. * @return string The date the post was last modified.
  3588. */
  3589. function get_lastpostmodified($timezone = 'server') {
  3590. $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
  3591. $lastpostdate = get_lastpostdate($timezone);
  3592. if ( $lastpostdate > $lastpostmodified )
  3593. $lastpostmodified = $lastpostdate;
  3594. return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
  3595. }
  3596. /**
  3597. * Retrieve latest post date data based on timezone.
  3598. *
  3599. * @access private
  3600. * @since 3.1.0
  3601. *
  3602. * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  3603. * @param string $field Field to check. Can be 'date' or 'modified'.
  3604. * @return string The date.
  3605. */
  3606. function _get_last_post_time( $timezone, $field ) {
  3607. global $wpdb;
  3608. if ( !in_array( $field, array( 'date', 'modified' ) ) )
  3609. return false;
  3610. $timezone = strtolower( $timezone );
  3611. $key = "lastpost{$field}:$timezone";
  3612. $date = wp_cache_get( $key, 'timeinfo' );
  3613. if ( !$date ) {
  3614. $add_seconds_server = date('Z');
  3615. $post_types = get_post_types( array( 'publicly_queryable' => true ) );
  3616. array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
  3617. $post_types = "'" . implode( "', '", $post_types ) . "'";
  3618. switch ( $timezone ) {
  3619. case 'gmt':
  3620. $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3621. break;
  3622. case 'blog':
  3623. $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3624. break;
  3625. case 'server':
  3626. $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3627. break;
  3628. }
  3629. if ( $date )
  3630. wp_cache_set( $key, $date, 'timeinfo' );
  3631. }
  3632. return $date;
  3633. }
  3634. /**
  3635. * Updates posts in cache.
  3636. *
  3637. * @usedby update_page_cache() Aliased by this function.
  3638. *
  3639. * @package WordPress
  3640. * @subpackage Cache
  3641. * @since 1.5.1
  3642. *
  3643. * @param array $posts Array of post objects
  3644. */
  3645. function update_post_cache(&$posts) {
  3646. if ( !$posts )
  3647. return;
  3648. foreach ( $posts as $post )
  3649. wp_cache_add($post->ID, $post, 'posts');
  3650. }
  3651. /**
  3652. * Will clean the post in the cache.
  3653. *
  3654. * Cleaning means delete from the cache of the post. Will call to clean the term
  3655. * object cache associated with the post ID.
  3656. *
  3657. * clean_post_cache() will call itself recursively for each child post.
  3658. *
  3659. * This function not run if $_wp_suspend_cache_invalidation is not empty. See
  3660. * wp_suspend_cache_invalidation().
  3661. *
  3662. * @package WordPress
  3663. * @subpackage Cache
  3664. * @since 2.0.0
  3665. *
  3666. * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
  3667. *
  3668. * @param int $id The Post ID in the cache to clean
  3669. */
  3670. function clean_post_cache($id) {
  3671. global $_wp_suspend_cache_invalidation, $wpdb;
  3672. if ( !empty($_wp_suspend_cache_invalidation) )
  3673. return;
  3674. $id = (int) $id;
  3675. if ( 0 === $id )
  3676. return;
  3677. wp_cache_delete($id, 'posts');
  3678. wp_cache_delete($id, 'post_meta');
  3679. clean_object_term_cache($id, 'post');
  3680. wp_cache_delete( 'wp_get_archives', 'general' );
  3681. do_action('clean_post_cache', $id);
  3682. if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
  3683. foreach ( $children as $cid ) {
  3684. // Loop detection
  3685. if ( $cid == $id )
  3686. continue;
  3687. clean_post_cache( $cid );
  3688. }
  3689. }
  3690. if ( is_multisite() )
  3691. wp_cache_delete( $wpdb->blogid . '-' . $id, 'global-posts' );
  3692. }
  3693. /**
  3694. * Alias of update_post_cache().
  3695. *
  3696. * @see update_post_cache() Posts and pages are the same, alias is intentional
  3697. *
  3698. * @package WordPress
  3699. * @subpackage Cache
  3700. * @since 1.5.1
  3701. *
  3702. * @param array $pages list of page objects
  3703. */
  3704. function update_page_cache(&$pages) {
  3705. update_post_cache($pages);
  3706. }
  3707. /**
  3708. * Will clean the page in the cache.
  3709. *
  3710. * Clean (read: delete) page from cache that matches $id. Will also clean cache
  3711. * associated with 'all_page_ids' and 'get_pages'.
  3712. *
  3713. * @package WordPress
  3714. * @subpackage Cache
  3715. * @since 2.0.0
  3716. *
  3717. * @uses do_action() Will call the 'clean_page_cache' hook action.
  3718. *
  3719. * @param int $id Page ID to clean
  3720. */
  3721. function clean_page_cache($id) {
  3722. clean_post_cache($id);
  3723. wp_cache_delete( 'all_page_ids', 'posts' );
  3724. wp_cache_delete( 'get_pages', 'posts' );
  3725. do_action('clean_page_cache', $id);
  3726. }
  3727. /**
  3728. * Call major cache updating functions for list of Post objects.
  3729. *
  3730. * @package WordPress
  3731. * @subpackage Cache
  3732. * @since 1.5.0
  3733. *
  3734. * @uses $wpdb
  3735. * @uses update_post_cache()
  3736. * @uses update_object_term_cache()
  3737. * @uses update_postmeta_cache()
  3738. *
  3739. * @param array $posts Array of Post objects
  3740. * @param string $post_type The post type of the posts in $posts. Default is 'post'.
  3741. * @param bool $update_term_cache Whether to update the term cache. Default is true.
  3742. * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
  3743. */
  3744. function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
  3745. // No point in doing all this work if we didn't match any posts.
  3746. if ( !$posts )
  3747. return;
  3748. update_post_cache($posts);
  3749. $post_ids = array();
  3750. foreach ( $posts as $post )
  3751. $post_ids[] = $post->ID;
  3752. if ( empty($post_type) )
  3753. $post_type = 'post';
  3754. if ( $update_term_cache ) {
  3755. if ( is_array($post_type) ) {
  3756. $ptypes = $post_type;
  3757. } elseif ( 'any' == $post_type ) {
  3758. // Just use the post_types in the supplied posts.
  3759. foreach ( $posts as $post )
  3760. $ptypes[] = $post->post_type;
  3761. $ptypes = array_unique($ptypes);
  3762. } else {
  3763. $ptypes = array($post_type);
  3764. }
  3765. if ( ! empty($ptypes) )
  3766. update_object_term_cache($post_ids, $ptypes);
  3767. }
  3768. if ( $update_meta_cache )
  3769. update_postmeta_cache($post_ids);
  3770. }
  3771. /**
  3772. * Updates metadata cache for list of post IDs.
  3773. *
  3774. * Performs SQL query to retrieve the metadata for the post IDs and updates the
  3775. * metadata cache for the posts. Therefore, the functions, which call this
  3776. * function, do not need to perform SQL queries on their own.
  3777. *
  3778. * @package WordPress
  3779. * @subpackage Cache
  3780. * @since 2.1.0
  3781. *
  3782. * @uses $wpdb
  3783. *
  3784. * @param array $post_ids List of post IDs.
  3785. * @return bool|array Returns false if there is nothing to update or an array of metadata.
  3786. */
  3787. function update_postmeta_cache($post_ids) {
  3788. return update_meta_cache('post', $post_ids);
  3789. }
  3790. /**
  3791. * Will clean the attachment in the cache.
  3792. *
  3793. * Cleaning means delete from the cache. Optionaly will clean the term
  3794. * object cache associated with the attachment ID.
  3795. *
  3796. * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
  3797. * wp_suspend_cache_invalidation().
  3798. *
  3799. * @package WordPress
  3800. * @subpackage Cache
  3801. * @since 3.0.0
  3802. *
  3803. * @uses do_action() Calls 'clean_attachment_cache' on $id.
  3804. *
  3805. * @param int $id The attachment ID in the cache to clean
  3806. * @param bool $clean_terms optional. Whether to clean terms cache
  3807. */
  3808. function clean_attachment_cache($id, $clean_terms = false) {
  3809. global $_wp_suspend_cache_invalidation;
  3810. if ( !empty($_wp_suspend_cache_invalidation) )
  3811. return;
  3812. $id = (int) $id;
  3813. wp_cache_delete($id, 'posts');
  3814. wp_cache_delete($id, 'post_meta');
  3815. if ( $clean_terms )
  3816. clean_object_term_cache($id, 'attachment');
  3817. do_action('clean_attachment_cache', $id);
  3818. }
  3819. //
  3820. // Hooks
  3821. //
  3822. /**
  3823. * Hook for managing future post transitions to published.
  3824. *
  3825. * @since 2.3.0
  3826. * @access private
  3827. * @uses $wpdb
  3828. * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
  3829. * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
  3830. *
  3831. * @param string $new_status New post status
  3832. * @param string $old_status Previous post status
  3833. * @param object $post Object type containing the post information
  3834. */
  3835. function _transition_post_status($new_status, $old_status, $post) {
  3836. global $wpdb;
  3837. if ( $old_status != 'publish' && $new_status == 'publish' ) {
  3838. // Reset GUID if transitioning to publish and it is empty
  3839. if ( '' == get_the_guid($post->ID) )
  3840. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
  3841. do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
  3842. }
  3843. // If published posts changed clear the lastpostmodified cache
  3844. if ( 'publish' == $new_status || 'publish' == $old_status) {
  3845. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  3846. wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
  3847. wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
  3848. }
  3849. }
  3850. // Always clears the hook in case the post status bounced from future to draft.
  3851. wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
  3852. }
  3853. /**
  3854. * Hook used to schedule publication for a post marked for the future.
  3855. *
  3856. * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
  3857. *
  3858. * @since 2.3.0
  3859. * @access private
  3860. *
  3861. * @param int $deprecated Not used. Can be set to null. Never implemented.
  3862. * Not marked as deprecated with _deprecated_argument() as it conflicts with
  3863. * wp_transition_post_status() and the default filter for _future_post_hook().
  3864. * @param object $post Object type containing the post information
  3865. */
  3866. function _future_post_hook( $deprecated = '', $post ) {
  3867. wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
  3868. wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
  3869. }
  3870. /**
  3871. * Hook to schedule pings and enclosures when a post is published.
  3872. *
  3873. * @since 2.3.0
  3874. * @access private
  3875. * @uses $wpdb
  3876. * @uses XMLRPC_REQUEST and APP_REQUEST constants.
  3877. * @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined.
  3878. * @uses do_action() Calls 'app_publish_post' on post ID if APP_REQUEST is defined.
  3879. *
  3880. * @param int $post_id The ID in the database table of the post being published
  3881. */
  3882. function _publish_post_hook($post_id) {
  3883. global $wpdb;
  3884. if ( defined('XMLRPC_REQUEST') )
  3885. do_action('xmlrpc_publish_post', $post_id);
  3886. if ( defined('APP_REQUEST') )
  3887. do_action('app_publish_post', $post_id);
  3888. if ( defined('WP_IMPORTING') )
  3889. return;
  3890. $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
  3891. if ( get_option('default_pingback_flag') ) {
  3892. $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
  3893. do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_pingme', 1 );
  3894. }
  3895. $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
  3896. do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_encloseme', 1 );
  3897. wp_schedule_single_event(time(), 'do_pings');
  3898. }
  3899. /**
  3900. * Hook used to prevent page/post cache and rewrite rules from staying dirty.
  3901. *
  3902. * Does two things. If the post is a page and has a template then it will
  3903. * update/add that template to the meta. For both pages and posts, it will clean
  3904. * the post cache to make sure that the cache updates to the changes done
  3905. * recently. For pages, the rewrite rules of WordPress are flushed to allow for
  3906. * any changes.
  3907. *
  3908. * The $post parameter, only uses 'post_type' property and 'page_template'
  3909. * property.
  3910. *
  3911. * @since 2.3.0
  3912. * @access private
  3913. * @uses $wp_rewrite Flushes Rewrite Rules.
  3914. *
  3915. * @param int $post_id The ID in the database table for the $post
  3916. * @param object $post Object type containing the post information
  3917. */
  3918. function _save_post_hook($post_id, $post) {
  3919. if ( $post->post_type == 'page' ) {
  3920. clean_page_cache($post_id);
  3921. // Avoid flushing rules for every post during import.
  3922. if ( !defined('WP_IMPORTING') ) {
  3923. global $wp_rewrite;
  3924. $wp_rewrite->flush_rules(false);
  3925. }
  3926. } else {
  3927. clean_post_cache($post_id);
  3928. }
  3929. }
  3930. /**
  3931. * Retrieve post ancestors and append to post ancestors property.
  3932. *
  3933. * Will only retrieve ancestors once, if property is already set, then nothing
  3934. * will be done. If there is not a parent post, or post ID and post parent ID
  3935. * are the same then nothing will be done.
  3936. *
  3937. * The parameter is passed by reference, so nothing needs to be returned. The
  3938. * property will be updated and can be referenced after the function is
  3939. * complete. The post parent will be an ancestor and the parent of the post
  3940. * parent will be an ancestor. There will only be two ancestors at the most.
  3941. *
  3942. * @since 2.5.0
  3943. * @access private
  3944. * @uses $wpdb
  3945. *
  3946. * @param object $_post Post data.
  3947. * @return null When nothing needs to be done.
  3948. */
  3949. function _get_post_ancestors(&$_post) {
  3950. global $wpdb;
  3951. if ( isset($_post->ancestors) )
  3952. return;
  3953. $_post->ancestors = array();
  3954. if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
  3955. return;
  3956. $id = $_post->ancestors[] = $_post->post_parent;
  3957. while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
  3958. // Loop detection: If the ancestor has been seen before, break.
  3959. if ( ( $ancestor == $_post->ID ) || in_array($ancestor, $_post->ancestors) )
  3960. break;
  3961. $id = $_post->ancestors[] = $ancestor;
  3962. }
  3963. }
  3964. /**
  3965. * Determines which fields of posts are to be saved in revisions.
  3966. *
  3967. * Does two things. If passed a post *array*, it will return a post array ready
  3968. * to be insterted into the posts table as a post revision. Otherwise, returns
  3969. * an array whose keys are the post fields to be saved for post revisions.
  3970. *
  3971. * @package WordPress
  3972. * @subpackage Post_Revisions
  3973. * @since 2.6.0
  3974. * @access private
  3975. * @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields.
  3976. *
  3977. * @param array $post Optional a post array to be processed for insertion as a post revision.
  3978. * @param bool $autosave optional Is the revision an autosave?
  3979. * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
  3980. */
  3981. function _wp_post_revision_fields( $post = null, $autosave = false ) {
  3982. static $fields = false;
  3983. if ( !$fields ) {
  3984. // Allow these to be versioned
  3985. $fields = array(
  3986. 'post_title' => __( 'Title' ),
  3987. 'post_content' => __( 'Content' ),
  3988. 'post_excerpt' => __( 'Excerpt' ),
  3989. );
  3990. // Runs only once
  3991. $fields = apply_filters( '_wp_post_revision_fields', $fields );
  3992. // WP uses these internally either in versioning or elsewhere - they cannot be versioned
  3993. foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
  3994. unset( $fields[$protect] );
  3995. }
  3996. if ( !is_array($post) )
  3997. return $fields;
  3998. $return = array();
  3999. foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
  4000. $return[$field] = $post[$field];
  4001. $return['post_parent'] = $post['ID'];
  4002. $return['post_status'] = 'inherit';
  4003. $return['post_type'] = 'revision';
  4004. $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
  4005. $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
  4006. $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
  4007. return $return;
  4008. }
  4009. /**
  4010. * Saves an already existing post as a post revision.
  4011. *
  4012. * Typically used immediately prior to post updates.
  4013. *
  4014. * @package WordPress
  4015. * @subpackage Post_Revisions
  4016. * @since 2.6.0
  4017. *
  4018. * @uses _wp_put_post_revision()
  4019. *
  4020. * @param int $post_id The ID of the post to save as a revision.
  4021. * @return mixed Null or 0 if error, new revision ID, if success.
  4022. */
  4023. function wp_save_post_revision( $post_id ) {
  4024. // We do autosaves manually with wp_create_post_autosave()
  4025. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
  4026. return;
  4027. // WP_POST_REVISIONS = 0, false
  4028. if ( ! WP_POST_REVISIONS )
  4029. return;
  4030. if ( !$post = get_post( $post_id, ARRAY_A ) )
  4031. return;
  4032. if ( !post_type_supports($post['post_type'], 'revisions') )
  4033. return;
  4034. $return = _wp_put_post_revision( $post );
  4035. // WP_POST_REVISIONS = true (default), -1
  4036. if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
  4037. return $return;
  4038. // all revisions and (possibly) one autosave
  4039. $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
  4040. // WP_POST_REVISIONS = (int) (# of autosaves to save)
  4041. $delete = count($revisions) - WP_POST_REVISIONS;
  4042. if ( $delete < 1 )
  4043. return $return;
  4044. $revisions = array_slice( $revisions, 0, $delete );
  4045. for ( $i = 0; isset($revisions[$i]); $i++ ) {
  4046. if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
  4047. continue;
  4048. wp_delete_post_revision( $revisions[$i]->ID );
  4049. }
  4050. return $return;
  4051. }
  4052. /**
  4053. * Retrieve the autosaved data of the specified post.
  4054. *
  4055. * Returns a post object containing the information that was autosaved for the
  4056. * specified post.
  4057. *
  4058. * @package WordPress
  4059. * @subpackage Post_Revisions
  4060. * @since 2.6.0
  4061. *
  4062. * @param int $post_id The post ID.
  4063. * @return object|bool The autosaved data or false on failure or when no autosave exists.
  4064. */
  4065. function wp_get_post_autosave( $post_id ) {
  4066. if ( !$post = get_post( $post_id ) )
  4067. return false;
  4068. $q = array(
  4069. 'name' => "{$post->ID}-autosave",
  4070. 'post_parent' => $post->ID,
  4071. 'post_type' => 'revision',
  4072. 'post_status' => 'inherit'
  4073. );
  4074. // Use WP_Query so that the result gets cached
  4075. $autosave_query = new WP_Query;
  4076. add_action( 'parse_query', '_wp_get_post_autosave_hack' );
  4077. $autosave = $autosave_query->query( $q );
  4078. remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
  4079. if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
  4080. return $autosave[0];
  4081. return false;
  4082. }
  4083. /**
  4084. * Internally used to hack WP_Query into submission.
  4085. *
  4086. * @package WordPress
  4087. * @subpackage Post_Revisions
  4088. * @since 2.6.0
  4089. *
  4090. * @param object $query WP_Query object
  4091. */
  4092. function _wp_get_post_autosave_hack( $query ) {
  4093. $query->is_single = false;
  4094. }
  4095. /**
  4096. * Determines if the specified post is a revision.
  4097. *
  4098. * @package WordPress
  4099. * @subpackage Post_Revisions
  4100. * @since 2.6.0
  4101. *
  4102. * @param int|object $post Post ID or post object.
  4103. * @return bool|int False if not a revision, ID of revision's parent otherwise.
  4104. */
  4105. function wp_is_post_revision( $post ) {
  4106. if ( !$post = wp_get_post_revision( $post ) )
  4107. return false;
  4108. return (int) $post->post_parent;
  4109. }
  4110. /**
  4111. * Determines if the specified post is an autosave.
  4112. *
  4113. * @package WordPress
  4114. * @subpackage Post_Revisions
  4115. * @since 2.6.0
  4116. *
  4117. * @param int|object $post Post ID or post object.
  4118. * @return bool|int False if not a revision, ID of autosave's parent otherwise
  4119. */
  4120. function wp_is_post_autosave( $post ) {
  4121. if ( !$post = wp_get_post_revision( $post ) )
  4122. return false;
  4123. if ( "{$post->post_parent}-autosave" !== $post->post_name )
  4124. return false;
  4125. return (int) $post->post_parent;
  4126. }
  4127. /**
  4128. * Inserts post data into the posts table as a post revision.
  4129. *
  4130. * @package WordPress
  4131. * @subpackage Post_Revisions
  4132. * @since 2.6.0
  4133. *
  4134. * @uses wp_insert_post()
  4135. *
  4136. * @param int|object|array $post Post ID, post object OR post array.
  4137. * @param bool $autosave Optional. Is the revision an autosave?
  4138. * @return mixed Null or 0 if error, new revision ID if success.
  4139. */
  4140. function _wp_put_post_revision( $post = null, $autosave = false ) {
  4141. if ( is_object($post) )
  4142. $post = get_object_vars( $post );
  4143. elseif ( !is_array($post) )
  4144. $post = get_post($post, ARRAY_A);
  4145. if ( !$post || empty($post['ID']) )
  4146. return;
  4147. if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
  4148. return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
  4149. $post = _wp_post_revision_fields( $post, $autosave );
  4150. $post = add_magic_quotes($post); //since data is from db
  4151. $revision_id = wp_insert_post( $post );
  4152. if ( is_wp_error($revision_id) )
  4153. return $revision_id;
  4154. if ( $revision_id )
  4155. do_action( '_wp_put_post_revision', $revision_id );
  4156. return $revision_id;
  4157. }
  4158. /**
  4159. * Gets a post revision.
  4160. *
  4161. * @package WordPress
  4162. * @subpackage Post_Revisions
  4163. * @since 2.6.0
  4164. *
  4165. * @uses get_post()
  4166. *
  4167. * @param int|object $post Post ID or post object
  4168. * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
  4169. * @param string $filter Optional sanitation filter. @see sanitize_post()
  4170. * @return mixed Null if error or post object if success
  4171. */
  4172. function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
  4173. $null = null;
  4174. if ( !$revision = get_post( $post, OBJECT, $filter ) )
  4175. return $revision;
  4176. if ( 'revision' !== $revision->post_type )
  4177. return $null;
  4178. if ( $output == OBJECT ) {
  4179. return $revision;
  4180. } elseif ( $output == ARRAY_A ) {
  4181. $_revision = get_object_vars($revision);
  4182. return $_revision;
  4183. } elseif ( $output == ARRAY_N ) {
  4184. $_revision = array_values(get_object_vars($revision));
  4185. return $_revision;
  4186. }
  4187. return $revision;
  4188. }
  4189. /**
  4190. * Restores a post to the specified revision.
  4191. *
  4192. * Can restore a past revision using all fields of the post revision, or only selected fields.
  4193. *
  4194. * @package WordPress
  4195. * @subpackage Post_Revisions
  4196. * @since 2.6.0
  4197. *
  4198. * @uses wp_get_post_revision()
  4199. * @uses wp_update_post()
  4200. * @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post()
  4201. * is successful.
  4202. *
  4203. * @param int|object $revision_id Revision ID or revision object.
  4204. * @param array $fields Optional. What fields to restore from. Defaults to all.
  4205. * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
  4206. */
  4207. function wp_restore_post_revision( $revision_id, $fields = null ) {
  4208. if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
  4209. return $revision;
  4210. if ( !is_array( $fields ) )
  4211. $fields = array_keys( _wp_post_revision_fields() );
  4212. $update = array();
  4213. foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
  4214. $update[$field] = $revision[$field];
  4215. if ( !$update )
  4216. return false;
  4217. $update['ID'] = $revision['post_parent'];
  4218. $update = add_magic_quotes( $update ); //since data is from db
  4219. $post_id = wp_update_post( $update );
  4220. if ( is_wp_error( $post_id ) )
  4221. return $post_id;
  4222. if ( $post_id )
  4223. do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
  4224. return $post_id;
  4225. }
  4226. /**
  4227. * Deletes a revision.
  4228. *
  4229. * Deletes the row from the posts table corresponding to the specified revision.
  4230. *
  4231. * @package WordPress
  4232. * @subpackage Post_Revisions
  4233. * @since 2.6.0
  4234. *
  4235. * @uses wp_get_post_revision()
  4236. * @uses wp_delete_post()
  4237. *
  4238. * @param int|object $revision_id Revision ID or revision object.
  4239. * @return mixed Null or WP_Error if error, deleted post if success.
  4240. */
  4241. function wp_delete_post_revision( $revision_id ) {
  4242. if ( !$revision = wp_get_post_revision( $revision_id ) )
  4243. return $revision;
  4244. $delete = wp_delete_post( $revision->ID );
  4245. if ( is_wp_error( $delete ) )
  4246. return $delete;
  4247. if ( $delete )
  4248. do_action( 'wp_delete_post_revision', $revision->ID, $revision );
  4249. return $delete;
  4250. }
  4251. /**
  4252. * Returns all revisions of specified post.
  4253. *
  4254. * @package WordPress
  4255. * @subpackage Post_Revisions
  4256. * @since 2.6.0
  4257. *
  4258. * @uses get_children()
  4259. *
  4260. * @param int|object $post_id Post ID or post object
  4261. * @return array empty if no revisions
  4262. */
  4263. function wp_get_post_revisions( $post_id = 0, $args = null ) {
  4264. if ( ! WP_POST_REVISIONS )
  4265. return array();
  4266. if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
  4267. return array();
  4268. $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
  4269. $args = wp_parse_args( $args, $defaults );
  4270. $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
  4271. if ( !$revisions = get_children( $args ) )
  4272. return array();
  4273. return $revisions;
  4274. }
  4275. function _set_preview($post) {
  4276. if ( ! is_object($post) )
  4277. return $post;
  4278. $preview = wp_get_post_autosave($post->ID);
  4279. if ( ! is_object($preview) )
  4280. return $post;
  4281. $preview = sanitize_post($preview);
  4282. $post->post_content = $preview->post_content;
  4283. $post->post_title = $preview->post_title;
  4284. $post->post_excerpt = $preview->post_excerpt;
  4285. return $post;
  4286. }
  4287. function _show_post_preview() {
  4288. if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
  4289. $id = (int) $_GET['preview_id'];
  4290. if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
  4291. wp_die( __('You do not have permission to preview drafts.') );
  4292. add_filter('the_preview', '_set_preview');
  4293. }
  4294. }
  4295. /**
  4296. * Returns the post's parent's post_ID
  4297. *
  4298. * @since 3.1.0
  4299. *
  4300. * @param int $post_id
  4301. *
  4302. * @return int|bool false on error
  4303. */
  4304. function wp_get_post_parent_id( $post_ID ) {
  4305. $post = get_post( $post_ID );
  4306. if ( !$post || is_wp_error( $post ) )
  4307. return false;
  4308. return (int) $post->post_parent;
  4309. }
  4310. /**
  4311. * Checks the given subset of the post hierarchy for hierarchy loops.
  4312. * Prevents loops from forming and breaks those that it finds.
  4313. *
  4314. * Attached to the wp_insert_post_parent filter.
  4315. *
  4316. * @since 3.1.0
  4317. * @uses wp_find_hierarchy_loop()
  4318. *
  4319. * @param int $post_parent ID of the parent for the post we're checking.
  4320. * @parem int $post_ID ID of the post we're checking.
  4321. *
  4322. * @return int The new post_parent for the post.
  4323. */
  4324. function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
  4325. // Nothing fancy here - bail
  4326. if ( !$post_parent )
  4327. return 0;
  4328. // New post can't cause a loop
  4329. if ( empty( $post_ID ) )
  4330. return $post_parent;
  4331. // Can't be its own parent
  4332. if ( $post_parent == $post_ID )
  4333. return 0;
  4334. // Now look for larger loops
  4335. if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
  4336. return $post_parent; // No loop
  4337. // Setting $post_parent to the given value causes a loop
  4338. if ( isset( $loop[$post_ID] ) )
  4339. return 0;
  4340. // There's a loop, but it doesn't contain $post_ID. Break the loop.
  4341. foreach ( array_keys( $loop ) as $loop_member )
  4342. wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
  4343. return $post_parent;
  4344. }
  4345. /**
  4346. * Returns an array of post format slugs to their translated and pretty display versions
  4347. *
  4348. * @since 3.1.0
  4349. *
  4350. * @return array The array of translations
  4351. */
  4352. function get_post_format_strings() {
  4353. $strings = array(
  4354. 'standard' => _x( 'Standard', 'Post format' ), // Special case. any value that evals to false will be considered standard
  4355. 'aside' => _x( 'Aside', 'Post format' ),
  4356. 'chat' => _x( 'Chat', 'Post format' ),
  4357. 'gallery' => _x( 'Gallery', 'Post format' ),
  4358. 'link' => _x( 'Link', 'Post format' ),
  4359. 'image' => _x( 'Image', 'Post format' ),
  4360. 'quote' => _x( 'Quote', 'Post format' ),
  4361. 'status' => _x( 'Status', 'Post format' ),
  4362. 'video' => _x( 'Video', 'Post format' ),
  4363. 'audio' => _x( 'Audio', 'Post format' ),
  4364. );
  4365. return $strings;
  4366. }
  4367. /**
  4368. * Retrieves an array of post format slugs.
  4369. *
  4370. * @since 3.1.0
  4371. *
  4372. * @return array The array of post format slugs.
  4373. */
  4374. function get_post_format_slugs() {
  4375. // 3.2-early: use array_combine() and array_keys( get_post_format_strings() )
  4376. $slugs = array(
  4377. 'standard' => 'standard', // Special case. any value that evals to false will be considered standard
  4378. 'aside' => 'aside',
  4379. 'chat' => 'chat',
  4380. 'gallery' => 'gallery',
  4381. 'link' => 'link',
  4382. 'image' => 'image',
  4383. 'quote' => 'quote',
  4384. 'status' => 'status',
  4385. 'video' => 'video',
  4386. 'audio' => 'audio',
  4387. );
  4388. return $slugs;
  4389. }
  4390. /**
  4391. * Returns a pretty, translated version of a post format slug
  4392. *
  4393. * @since 3.1.0
  4394. *
  4395. * @param string $slug A post format slug
  4396. * @return string The translated post format name
  4397. */
  4398. function get_post_format_string( $slug ) {
  4399. $strings = get_post_format_strings();
  4400. if ( !$slug )
  4401. return $strings['standard'];
  4402. else
  4403. return ( isset( $strings[$slug] ) ) ? $strings[$slug] : '';
  4404. }
  4405. /**
  4406. * Sets a post thumbnail.
  4407. *
  4408. * @since 3.1.0
  4409. *
  4410. * @param int|object $post Post ID or object where thumbnail should be attached.
  4411. * @param int $thumbnail_id Thumbnail to attach.
  4412. * @return bool True on success, false on failure.
  4413. */
  4414. function set_post_thumbnail( $post, $thumbnail_id ) {
  4415. $post = get_post( $post );
  4416. $thumbnail_id = absint( $thumbnail_id );
  4417. if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
  4418. $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' );
  4419. if ( ! empty( $thumbnail_html ) ) {
  4420. update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
  4421. return true;
  4422. }
  4423. }
  4424. return false;
  4425. }
  4426. /**
  4427. * Returns a link to a post format index.
  4428. *
  4429. * @since 3.1.0
  4430. *
  4431. * @param $format string Post format
  4432. * @return string Link
  4433. */
  4434. function get_post_format_link( $format ) {
  4435. $term = get_term_by('slug', 'post-format-' . $format, 'post_format' );
  4436. if ( ! $term || is_wp_error( $term ) )
  4437. return false;
  4438. return get_term_link( $term );
  4439. }
  4440. /**
  4441. * Filters the request to allow for the format prefix.
  4442. *
  4443. * @access private
  4444. * @since 3.1.0
  4445. */
  4446. function _post_format_request( $qvs ) {
  4447. if ( ! isset( $qvs['post_format'] ) )
  4448. return $qvs;
  4449. $slugs = get_post_format_slugs();
  4450. if ( isset( $slugs[ $qvs['post_format'] ] ) )
  4451. $qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ];
  4452. $tax = get_taxonomy( 'post_format' );
  4453. $qvs['post_type'] = $tax->object_type;
  4454. return $qvs;
  4455. }
  4456. add_filter( 'request', '_post_format_request' );
  4457. /**
  4458. * Filters the post format term link to remove the format prefix.
  4459. *
  4460. * @access private
  4461. * @since 3.1.0
  4462. */
  4463. function _post_format_link( $link, $term, $taxonomy ) {
  4464. global $wp_rewrite;
  4465. if ( 'post_format' != $taxonomy )
  4466. return $link;
  4467. if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) {
  4468. return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link );
  4469. } else {
  4470. $link = remove_query_arg( 'post_format', $link );
  4471. return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link );
  4472. }
  4473. }
  4474. add_filter( 'term_link', '_post_format_link', 10, 3 );
  4475. /**
  4476. * Remove the post format prefix from the name property of the term object created by get_term().
  4477. *
  4478. * @access private
  4479. * @since 3.1.0
  4480. */
  4481. function _post_format_get_term( $term ) {
  4482. if ( isset( $term->slug ) ) {
  4483. $term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4484. }
  4485. return $term;
  4486. }
  4487. add_filter( 'get_post_format', '_post_format_get_term' );
  4488. /**
  4489. * Remove the post format prefix from the name property of the term objects created by get_terms().
  4490. *
  4491. * @access private
  4492. * @since 3.1.0
  4493. */
  4494. function _post_format_get_terms( $terms, $taxonomies, $args ) {
  4495. if ( in_array( 'post_format', (array) $taxonomies ) ) {
  4496. if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) {
  4497. foreach( $terms as $order => $name ) {
  4498. $terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) );
  4499. }
  4500. } else {
  4501. foreach ( (array) $terms as $order => $term ) {
  4502. if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
  4503. $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4504. }
  4505. }
  4506. }
  4507. }
  4508. return $terms;
  4509. }
  4510. add_filter( 'get_terms', '_post_format_get_terms', 10, 3 );
  4511. /**
  4512. * Remove the post format prefix from the name property of the term objects created by wp_get_object_terms().
  4513. *
  4514. * @access private
  4515. * @since 3.1.0
  4516. */
  4517. function _post_format_wp_get_object_terms( $terms ) {
  4518. foreach ( (array) $terms as $order => $term ) {
  4519. if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
  4520. $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4521. }
  4522. }
  4523. return $terms;
  4524. }
  4525. add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' );
  4526. ?>