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

/wp-includes/post.php

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