PageRenderTime 43ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/post.php

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