PageRenderTime 40ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/post.php

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