PageRenderTime 83ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/post.php

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