PageRenderTime 41ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/msw/dev/wp-includes/post.php

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