PageRenderTime 36ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/post.php

https://bitbucket.org/acipriani/madeinapulia.com
PHP | 5846 lines | 2473 code | 714 blank | 2659 comment | 684 complexity | 15e634132196410e34dcf50820fcd942 MD5 | raw file
Possible License(s): GPL-3.0, MIT, BSD-3-Clause, LGPL-2.1, GPL-2.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 `<!--more-->`. The 'extended' key has the content after the
  344. * `<!--more-->` 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|false 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|false 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 post statuses.
  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 to compare against
  932. * properties of the global `$wp_post_statuses objects`. Default empty array.
  933. * @param string $output Optional. The type of output to return, either 'names' 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|false 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() for accepted arguments.
  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 Optional. The logical operation to perform. 'or' means only one
  1020. * element from the array needs to match; 'and' means all elements
  1021. * must match. Accepts 'or' or 'and'. 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 = (bool) $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. * {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context}
  1406. * matching your post type. Example: `_x( 'Add New', 'product' );`.
  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 `name`.
  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 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 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 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 null|bool Null 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. * @param int $post_id Optional. The Post ID. Does not default to the ID of the
  2585. * global $post. Defualt 0.
  2586. * @param array $args Optional. Overwrite the defaults
  2587. * @return array List of post tags.
  2588. */
  2589. function wp_get_post_tags( $post_id = 0, $args = array() ) {
  2590. return wp_get_post_terms( $post_id, 'post_tag', $args);
  2591. }
  2592. /**
  2593. * Retrieve the terms for a post.
  2594. *
  2595. * There is only one default for this function, called 'fields' and by default
  2596. * is set to 'all'. There are other defaults that can be overridden in
  2597. * {@link wp_get_object_terms()}.
  2598. *
  2599. * @since 2.8.0
  2600. *
  2601. * @param int $post_id Optional. The Post ID. Does not default to the ID of the
  2602. * global $post. Default 0.
  2603. * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
  2604. * @param array $args Optional. {@link wp_get_object_terms()} arguments. Default empty array.
  2605. * @return array List of post tags.
  2606. */
  2607. function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
  2608. $post_id = (int) $post_id;
  2609. $defaults = array('fields' => 'all');
  2610. $args = wp_parse_args( $args, $defaults );
  2611. $tags = wp_get_object_terms($post_id, $taxonomy, $args);
  2612. return $tags;
  2613. }
  2614. /**
  2615. * Retrieve a number of recent posts.
  2616. *
  2617. * @since 1.0.0
  2618. *
  2619. * @see get_posts()
  2620. *
  2621. * @param array $args Optional. Arguments to retrieve posts. Default empty array.
  2622. * @param string $output Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
  2623. * @return array|bool Associative array if $output equals ARRAY_A, array or false if no results.
  2624. */
  2625. function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
  2626. if ( is_numeric( $args ) ) {
  2627. _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  2628. $args = array( 'numberposts' => absint( $args ) );
  2629. }
  2630. // Set default arguments.
  2631. $defaults = array(
  2632. 'numberposts' => 10, 'offset' => 0,
  2633. 'category' => 0, 'orderby' => 'post_date',
  2634. 'order' => 'DESC', 'include' => '',
  2635. 'exclude' => '', 'meta_key' => '',
  2636. 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
  2637. 'suppress_filters' => true
  2638. );
  2639. $r = wp_parse_args( $args, $defaults );
  2640. $results = get_posts( $r );
  2641. // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
  2642. if ( ARRAY_A == $output ){
  2643. foreach( $results as $key => $result ) {
  2644. $results[$key] = get_object_vars( $result );
  2645. }
  2646. return $results ? $results : array();
  2647. }
  2648. return $results ? $results : false;
  2649. }
  2650. /**
  2651. * Insert or update a post.
  2652. *
  2653. * If the $postarr parameter has 'ID' set to a value, then post will be updated.
  2654. *
  2655. * You can set the post date manually, by setting the values for 'post_date'
  2656. * and 'post_date_gmt' keys. You can close the comments or open the comments by
  2657. * setting the value for 'comment_status' key.
  2658. *
  2659. * @since 1.0.0
  2660. *
  2661. * @see sanitize_post()
  2662. * @global wpdb $wpdb WordPress database abstraction object.
  2663. *
  2664. * @param array $postarr {
  2665. * An array of elements that make up a post to update or insert.
  2666. *
  2667. * @type int $ID The post ID. If equal to something other than 0,
  2668. * the post with that ID will be updated. Default 0.
  2669. * @type string $post_status The post status. Default 'draft'.
  2670. * @type string $post_type The post type. Default 'post'.
  2671. * @type int $post_author The ID of the user who added the post. Default is
  2672. * the current user ID.
  2673. * @type bool $ping_status Whether the post can accept pings. Default is the
  2674. * value of 'default_ping_status' option.
  2675. * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
  2676. * @type int $menu_order The order it is displayed. Default 0.
  2677. * @type string $to_ping Space or carriage return-separated list of URLs to ping.
  2678. * Default empty string.
  2679. * @type string $pinged Space or carriage return-separated list of URLs that have
  2680. * been pinged. Default empty string.
  2681. * @type string $post_password The password to access the post. Default empty string.
  2682. * @type string $guid' Global Unique ID for referencing the post.
  2683. * @type string $post_content_filtered The filtered post content. Default empty string.
  2684. * @type string $post_excerpt The post excerpt. Default empty string.
  2685. * }
  2686. * @param bool $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
  2687. * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
  2688. */
  2689. function wp_insert_post( $postarr, $wp_error = false ) {
  2690. global $wpdb;
  2691. $user_id = get_current_user_id();
  2692. $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id,
  2693. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  2694. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  2695. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
  2696. 'post_content' => '', 'post_title' => '', 'context' => '');
  2697. $postarr = wp_parse_args($postarr, $defaults);
  2698. unset( $postarr[ 'filter' ] );
  2699. $postarr = sanitize_post($postarr, 'db');
  2700. // Are we updating or creating?
  2701. $post_ID = 0;
  2702. $update = false;
  2703. $guid = $postarr['guid'];
  2704. if ( ! empty( $postarr['ID'] ) ) {
  2705. $update = true;
  2706. // Get the post ID and GUID.
  2707. $post_ID = $postarr['ID'];
  2708. $post_before = get_post( $post_ID );
  2709. if ( is_null( $post_before ) ) {
  2710. if ( $wp_error ) {
  2711. return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
  2712. }
  2713. return 0;
  2714. }
  2715. $guid = get_post_field( 'guid', $post_ID );
  2716. $previous_status = get_post_field('post_status', $post_ID );
  2717. } else {
  2718. $previous_status = 'new';
  2719. }
  2720. $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
  2721. $post_title = $postarr['post_title'];
  2722. $post_content = $postarr['post_content'];
  2723. $post_excerpt = $postarr['post_excerpt'];
  2724. if ( isset( $postarr['post_name'] ) ) {
  2725. $post_name = $postarr['post_name'];
  2726. }
  2727. $maybe_empty = 'attachment' !== $post_type
  2728. && ! $post_content && ! $post_title && ! $post_excerpt
  2729. && post_type_supports( $post_type, 'editor' )
  2730. && post_type_supports( $post_type, 'title' )
  2731. && post_type_supports( $post_type, 'excerpt' );
  2732. /**
  2733. * Filter whether the post should be considered "empty".
  2734. *
  2735. * The post is considered "empty" if both:
  2736. * 1. The post type supports the title, editor, and excerpt fields
  2737. * 2. The title, editor, and excerpt fields are all empty
  2738. *
  2739. * Returning a truthy value to the filter will effectively short-circuit
  2740. * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
  2741. * will be returned instead.
  2742. *
  2743. * @since 3.3.0
  2744. *
  2745. * @param bool $maybe_empty Whether the post should be considered "empty".
  2746. * @param array $postarr Array of post data.
  2747. */
  2748. if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
  2749. if ( $wp_error ) {
  2750. return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
  2751. } else {
  2752. return 0;
  2753. }
  2754. }
  2755. $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
  2756. if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
  2757. $post_status = 'inherit';
  2758. }
  2759. if ( ! empty( $postarr['post_category'] ) ) {
  2760. // Filter out empty terms.
  2761. $post_category = array_filter( $postarr['post_category'] );
  2762. }
  2763. // Make sure we set a valid category.
  2764. if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
  2765. // 'post' requires at least one category.
  2766. if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
  2767. $post_category = array( get_option('default_category') );
  2768. } else {
  2769. $post_category = array();
  2770. }
  2771. }
  2772. // Don't allow contributors to set the post slug for pending review posts.
  2773. if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
  2774. $post_name = '';
  2775. }
  2776. /*
  2777. * Create a valid post name. Drafts and pending posts are allowed to have
  2778. * an empty post name.
  2779. */
  2780. if ( empty($post_name) ) {
  2781. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
  2782. $post_name = sanitize_title($post_title);
  2783. } else {
  2784. $post_name = '';
  2785. }
  2786. } else {
  2787. // On updates, we need to check to see if it's using the old, fixed sanitization context.
  2788. $check_name = sanitize_title( $post_name, '', 'old-save' );
  2789. if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
  2790. $post_name = $check_name;
  2791. } else { // new post, or slug has changed.
  2792. $post_name = sanitize_title($post_name);
  2793. }
  2794. }
  2795. /*
  2796. * If the post date is empty (due to having been new or a draft) and status
  2797. * is not 'draft' or 'pending', set date to now.
  2798. */
  2799. if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
  2800. $post_date = current_time( 'mysql' );
  2801. } else {
  2802. $post_date = $postarr['post_date'];
  2803. }
  2804. // Validate the date.
  2805. $mm = substr( $post_date, 5, 2 );
  2806. $jj = substr( $post_date, 8, 2 );
  2807. $aa = substr( $post_date, 0, 4 );
  2808. $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
  2809. if ( ! $valid_date ) {
  2810. if ( $wp_error ) {
  2811. return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
  2812. } else {
  2813. return 0;
  2814. }
  2815. }
  2816. if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
  2817. if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
  2818. $post_date_gmt = get_gmt_from_date( $post_date );
  2819. } else {
  2820. $post_date_gmt = '0000-00-00 00:00:00';
  2821. }
  2822. } else {
  2823. $post_date_gmt = $postarr['post_date_gmt'];
  2824. }
  2825. if ( $update || '0000-00-00 00:00:00' == $post_date ) {
  2826. $post_modified = current_time( 'mysql' );
  2827. $post_modified_gmt = current_time( 'mysql', 1 );
  2828. } else {
  2829. $post_modified = $post_date;
  2830. $post_modified_gmt = $post_date_gmt;
  2831. }
  2832. if ( 'attachment' !== $post_type ) {
  2833. if ( 'publish' == $post_status ) {
  2834. $now = gmdate('Y-m-d H:i:59');
  2835. if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
  2836. $post_status = 'future';
  2837. }
  2838. } elseif( 'future' == $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 = 'publish';
  2842. }
  2843. }
  2844. }
  2845. if ( empty( $postarr['comment_status'] ) ) {
  2846. if ( $update ) {
  2847. $comment_status = 'closed';
  2848. } else {
  2849. $comment_status = get_option('default_comment_status');
  2850. }
  2851. } else {
  2852. $comment_status = $postarr['comment_status'];
  2853. }
  2854. // These variables are needed by compact() later.
  2855. $post_content_filtered = $postarr['post_content_filtered'];
  2856. $post_author = empty( $postarr['post_author'] ) ? $user_id : $postarr['post_author'];
  2857. $ping_status = empty( $postarr['ping_status'] ) ? get_option( 'default_ping_status' ) : $postarr['ping_status'];
  2858. $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
  2859. $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
  2860. $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
  2861. /*
  2862. * The 'wp_insert_post_parent' filter expects all variables to be present.
  2863. * Previously, these variables would have already been extracted
  2864. */
  2865. if ( isset( $postarr['menu_order'] ) ) {
  2866. $menu_order = (int) $postarr['menu_order'];
  2867. } else {
  2868. $menu_order = 0;
  2869. }
  2870. $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
  2871. if ( 'private' == $post_status ) {
  2872. $post_password = '';
  2873. }
  2874. if ( isset( $postarr['post_parent'] ) ) {
  2875. $post_parent = (int) $postarr['post_parent'];
  2876. } else {
  2877. $post_parent = 0;
  2878. }
  2879. /**
  2880. * Filter the post parent -- used to check for and prevent hierarchy loops.
  2881. *
  2882. * @since 3.1.0
  2883. *
  2884. * @param int $post_parent Post parent ID.
  2885. * @param int $post_ID Post ID.
  2886. * @param array $new_postarr Array of parsed post data.
  2887. * @param array $postarr Array of sanitized, but otherwise unmodified post data.
  2888. */
  2889. $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
  2890. $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
  2891. // Don't unslash.
  2892. $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
  2893. // Expected_slashed (everything!).
  2894. $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' );
  2895. if ( 'attachment' === $post_type ) {
  2896. /**
  2897. * Filter attachment post data before it is updated in or added to the database.
  2898. *
  2899. * @since 3.9.0
  2900. *
  2901. * @param array $data An array of sanitized attachment post data.
  2902. * @param array $postarr An array of unsanitized attachment post data.
  2903. */
  2904. $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
  2905. } else {
  2906. /**
  2907. * Filter slashed post data just before it is inserted into the database.
  2908. *
  2909. * @since 2.7.0
  2910. *
  2911. * @param array $data An array of slashed post data.
  2912. * @param array $postarr An array of sanitized, but otherwise unmodified post data.
  2913. */
  2914. $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
  2915. }
  2916. $data = wp_unslash( $data );
  2917. $where = array( 'ID' => $post_ID );
  2918. if ( $update ) {
  2919. /**
  2920. * Fires immediately before an existing post is updated in the database.
  2921. *
  2922. * @since 2.5.0
  2923. *
  2924. * @param int $post_ID Post ID.
  2925. * @param array $data Array of unslashed post data.
  2926. */
  2927. do_action( 'pre_post_update', $post_ID, $data );
  2928. if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  2929. if ( $wp_error ) {
  2930. return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  2931. } else {
  2932. return 0;
  2933. }
  2934. }
  2935. } else {
  2936. // If there is a suggested ID, use it if not already present.
  2937. if ( ! empty( $import_id ) ) {
  2938. $import_id = (int) $import_id;
  2939. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  2940. $data['ID'] = $import_id;
  2941. }
  2942. }
  2943. if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
  2944. if ( $wp_error ) {
  2945. return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
  2946. } else {
  2947. return 0;
  2948. }
  2949. }
  2950. $post_ID = (int) $wpdb->insert_id;
  2951. // Use the newly generated $post_ID.
  2952. $where = array( 'ID' => $post_ID );
  2953. }
  2954. if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
  2955. $data['post_name'] = sanitize_title( $data['post_title'], $post_ID );
  2956. $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  2957. }
  2958. if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
  2959. wp_set_post_categories( $post_ID, $post_category );
  2960. }
  2961. if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
  2962. wp_set_post_tags( $post_ID, $postarr['tags_input'] );
  2963. }
  2964. // New-style support for all custom taxonomies.
  2965. if ( ! empty( $postarr['tax_input'] ) ) {
  2966. foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
  2967. $taxonomy_obj = get_taxonomy($taxonomy);
  2968. // array = hierarchical, string = non-hierarchical.
  2969. if ( is_array( $tags ) ) {
  2970. $tags = array_filter($tags);
  2971. }
  2972. if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
  2973. wp_set_post_terms( $post_ID, $tags, $taxonomy );
  2974. }
  2975. }
  2976. }
  2977. $current_guid = get_post_field( 'guid', $post_ID );
  2978. // Set GUID.
  2979. if ( ! $update && '' == $current_guid ) {
  2980. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  2981. }
  2982. if ( 'attachment' === $postarr['post_type'] ) {
  2983. if ( ! empty( $postarr['file'] ) ) {
  2984. update_attached_file( $post_ID, $postarr['file'] );
  2985. }
  2986. if ( ! empty( $postarr['context'] ) ) {
  2987. add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
  2988. }
  2989. }
  2990. clean_post_cache( $post_ID );
  2991. $post = get_post( $post_ID );
  2992. if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
  2993. $post->page_template = $postarr['page_template'];
  2994. $page_templates = wp_get_theme()->get_page_templates( $post );
  2995. if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
  2996. if ( $wp_error ) {
  2997. return new WP_Error('invalid_page_template', __('The page template is invalid.'));
  2998. } else {
  2999. return 0;
  3000. }
  3001. }
  3002. update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
  3003. }
  3004. if ( 'attachment' !== $postarr['post_type'] ) {
  3005. wp_transition_post_status( $data['post_status'], $previous_status, $post );
  3006. } else {
  3007. if ( $update ) {
  3008. /**
  3009. * Fires once an existing attachment has been updated.
  3010. *
  3011. * @since 2.0.0
  3012. *
  3013. * @param int $post_ID Attachment ID.
  3014. */
  3015. do_action( 'edit_attachment', $post_ID );
  3016. } else {
  3017. /**
  3018. * Fires once an attachment has been added.
  3019. *
  3020. * @since 2.0.0
  3021. *
  3022. * @param int $post_ID Attachment ID.
  3023. */
  3024. do_action( 'add_attachment', $post_ID );
  3025. }
  3026. return $post_ID;
  3027. }
  3028. if ( $update ) {
  3029. /**
  3030. * Fires once an existing post has been updated.
  3031. *
  3032. * @since 1.2.0
  3033. *
  3034. * @param int $post_ID Post ID.
  3035. * @param WP_Post $post Post object.
  3036. */
  3037. do_action( 'edit_post', $post_ID, $post );
  3038. $post_after = get_post($post_ID);
  3039. /**
  3040. * Fires once an existing post has been updated.
  3041. *
  3042. * @since 3.0.0
  3043. *
  3044. * @param int $post_ID Post ID.
  3045. * @param WP_Post $post_after Post object following the update.
  3046. * @param WP_Post $post_before Post object before the update.
  3047. */
  3048. do_action( 'post_updated', $post_ID, $post_after, $post_before);
  3049. }
  3050. /**
  3051. * Fires once a post has been saved.
  3052. *
  3053. * The dynamic portion of the hook name, `$post->post_type`, refers to
  3054. * the post type slug.
  3055. *
  3056. * @since 3.7.0
  3057. *
  3058. * @param int $post_ID Post ID.
  3059. * @param WP_Post $post Post object.
  3060. * @param bool $update Whether this is an existing post being updated or not.
  3061. */
  3062. do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
  3063. /**
  3064. * Fires once a post has been saved.
  3065. *
  3066. * @since 1.5.0
  3067. *
  3068. * @param int $post_ID Post ID.
  3069. * @param WP_Post $post Post object.
  3070. * @param bool $update Whether this is an existing post being updated or not.
  3071. */
  3072. do_action( 'save_post', $post_ID, $post, $update );
  3073. /**
  3074. * Fires once a post has been saved.
  3075. *
  3076. * @since 2.0.0
  3077. *
  3078. * @param int $post_ID Post ID.
  3079. * @param WP_Post $post Post object.
  3080. * @param bool $update Whether this is an existing post being updated or not.
  3081. */
  3082. do_action( 'wp_insert_post', $post_ID, $post, $update );
  3083. return $post_ID;
  3084. }
  3085. /**
  3086. * Update a post with new post data.
  3087. *
  3088. * The date does not have to be set for drafts. You can set the date and it will
  3089. * not be overridden.
  3090. *
  3091. * @since 1.0.0
  3092. *
  3093. * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
  3094. * objects are not. Default array.
  3095. * @param bool $wp_error Optional. Allow return of WP_Error on failure. Default false.
  3096. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  3097. */
  3098. function wp_update_post( $postarr = array(), $wp_error = false ) {
  3099. if ( is_object($postarr) ) {
  3100. // Non-escaped post was passed.
  3101. $postarr = get_object_vars($postarr);
  3102. $postarr = wp_slash($postarr);
  3103. }
  3104. // First, get all of the original fields.
  3105. $post = get_post($postarr['ID'], ARRAY_A);
  3106. if ( is_null( $post ) ) {
  3107. if ( $wp_error )
  3108. return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
  3109. return 0;
  3110. }
  3111. // Escape data pulled from DB.
  3112. $post = wp_slash($post);
  3113. // Passed post category list overwrites existing category list if not empty.
  3114. if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
  3115. && 0 != count($postarr['post_category']) )
  3116. $post_cats = $postarr['post_category'];
  3117. else
  3118. $post_cats = $post['post_category'];
  3119. // Drafts shouldn't be assigned a date unless explicitly done so by the user.
  3120. if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
  3121. ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  3122. $clear_date = true;
  3123. else
  3124. $clear_date = false;
  3125. // Merge old and new fields with new fields overwriting old ones.
  3126. $postarr = array_merge($post, $postarr);
  3127. $postarr['post_category'] = $post_cats;
  3128. if ( $clear_date ) {
  3129. $postarr['post_date'] = current_time('mysql');
  3130. $postarr['post_date_gmt'] = '';
  3131. }
  3132. if ($postarr['post_type'] == 'attachment')
  3133. return wp_insert_attachment($postarr);
  3134. return wp_insert_post( $postarr, $wp_error );
  3135. }
  3136. /**
  3137. * Publish a post by transitioning the post status.
  3138. *
  3139. * @since 2.1.0
  3140. *
  3141. * @global wpdb $wpdb WordPress database abstraction object.
  3142. *
  3143. * @param int|WP_Post $post Post ID or post object.
  3144. */
  3145. function wp_publish_post( $post ) {
  3146. global $wpdb;
  3147. if ( ! $post = get_post( $post ) )
  3148. return;
  3149. if ( 'publish' == $post->post_status )
  3150. return;
  3151. $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
  3152. clean_post_cache( $post->ID );
  3153. $old_status = $post->post_status;
  3154. $post->post_status = 'publish';
  3155. wp_transition_post_status( 'publish', $old_status, $post );
  3156. /** This action is documented in wp-includes/post.php */
  3157. do_action( 'edit_post', $post->ID, $post );
  3158. /** This action is documented in wp-includes/post.php */
  3159. do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
  3160. /** This action is documented in wp-includes/post.php */
  3161. do_action( 'save_post', $post->ID, $post, true );
  3162. /** This action is documented in wp-includes/post.php */
  3163. do_action( 'wp_insert_post', $post->ID, $post, true );
  3164. }
  3165. /**
  3166. * Publish future post and make sure post ID has future post status.
  3167. *
  3168. * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
  3169. * from publishing drafts, etc.
  3170. *
  3171. * @since 2.5.0
  3172. *
  3173. * @param int|WP_Post $post_id Post ID or post object.
  3174. * @return null Nothing is returned. Which can mean that no action is required
  3175. * or post was published.
  3176. */
  3177. function check_and_publish_future_post( $post_id ) {
  3178. $post = get_post($post_id);
  3179. if ( empty($post) )
  3180. return;
  3181. if ( 'future' != $post->post_status )
  3182. return;
  3183. $time = strtotime( $post->post_date_gmt . ' GMT' );
  3184. // Uh oh, someone jumped the gun!
  3185. if ( $time > time() ) {
  3186. wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
  3187. wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  3188. return;
  3189. }
  3190. return wp_publish_post($post_id);
  3191. }
  3192. /**
  3193. * Computes a unique slug for the post, when given the desired slug and some post details.
  3194. *
  3195. * @since 2.8.0
  3196. *
  3197. * @global wpdb $wpdb WordPress database abstraction object.
  3198. * @global WP_Rewrite $wp_rewrite
  3199. *
  3200. * @param string $slug The desired slug (post_name).
  3201. * @param int $post_ID Post ID.
  3202. * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
  3203. * @param string $post_type Post type.
  3204. * @param int $post_parent Post parent ID.
  3205. * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  3206. */
  3207. function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
  3208. if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
  3209. return $slug;
  3210. global $wpdb, $wp_rewrite;
  3211. $original_slug = $slug;
  3212. $feeds = $wp_rewrite->feeds;
  3213. if ( ! is_array( $feeds ) )
  3214. $feeds = array();
  3215. if ( 'attachment' == $post_type ) {
  3216. // Attachment slugs must be unique across all types.
  3217. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  3218. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
  3219. /**
  3220. * Filter whether the post slug would make a bad attachment slug.
  3221. *
  3222. * @since 3.1.0
  3223. *
  3224. * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
  3225. * @param string $slug The post slug.
  3226. */
  3227. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
  3228. $suffix = 2;
  3229. do {
  3230. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  3231. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
  3232. $suffix++;
  3233. } while ( $post_name_check );
  3234. $slug = $alt_post_name;
  3235. }
  3236. } elseif ( is_post_type_hierarchical( $post_type ) ) {
  3237. if ( 'nav_menu_item' == $post_type )
  3238. return $slug;
  3239. /*
  3240. * Page slugs must be unique within their own trees. Pages are in a separate
  3241. * namespace than posts so page slugs are allowed to overlap post slugs.
  3242. */
  3243. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1";
  3244. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
  3245. /**
  3246. * Filter whether the post slug would make a bad hierarchical post slug.
  3247. *
  3248. * @since 3.1.0
  3249. *
  3250. * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
  3251. * @param string $slug The post slug.
  3252. * @param string $post_type Post type.
  3253. * @param int $post_parent Post parent ID.
  3254. */
  3255. 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 ) ) {
  3256. $suffix = 2;
  3257. do {
  3258. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  3259. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
  3260. $suffix++;
  3261. } while ( $post_name_check );
  3262. $slug = $alt_post_name;
  3263. }
  3264. } else {
  3265. // Post slugs must be unique across all posts.
  3266. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  3267. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
  3268. /**
  3269. * Filter whether the post slug would be bad as a flat slug.
  3270. *
  3271. * @since 3.1.0
  3272. *
  3273. * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
  3274. * @param string $slug The post slug.
  3275. * @param string $post_type Post type.
  3276. */
  3277. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
  3278. $suffix = 2;
  3279. do {
  3280. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  3281. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
  3282. $suffix++;
  3283. } while ( $post_name_check );
  3284. $slug = $alt_post_name;
  3285. }
  3286. }
  3287. /**
  3288. * Filter the unique post slug.
  3289. *
  3290. * @since 3.3.0
  3291. *
  3292. * @param string $slug The post slug.
  3293. * @param int $post_ID Post ID.
  3294. * @param string $post_status The post status.
  3295. * @param string $post_type Post type.
  3296. * @param int $post_parent Post parent ID
  3297. * @param string $original_slug The original post slug.
  3298. */
  3299. return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
  3300. }
  3301. /**
  3302. * Truncate a post slug.
  3303. *
  3304. * @since 3.6.0
  3305. * @access private
  3306. *
  3307. * @see utf8_uri_encode()
  3308. *
  3309. * @param string $slug The slug to truncate.
  3310. * @param int $length Optional. Max length of the slug. Default 200 (characters).
  3311. * @return string The truncated slug.
  3312. */
  3313. function _truncate_post_slug( $slug, $length = 200 ) {
  3314. if ( strlen( $slug ) > $length ) {
  3315. $decoded_slug = urldecode( $slug );
  3316. if ( $decoded_slug === $slug )
  3317. $slug = substr( $slug, 0, $length );
  3318. else
  3319. $slug = utf8_uri_encode( $decoded_slug, $length );
  3320. }
  3321. return rtrim( $slug, '-' );
  3322. }
  3323. /**
  3324. * Add tags to a post.
  3325. *
  3326. * @see wp_set_post_tags()
  3327. *
  3328. * @since 2.3.0
  3329. *
  3330. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  3331. * Default 0.
  3332. * @param string $tags Optional. The tags to set for the post, separated by commas. Default empty.
  3333. * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise.
  3334. */
  3335. function wp_add_post_tags( $post_id = 0, $tags = '' ) {
  3336. return wp_set_post_tags($post_id, $tags, true);
  3337. }
  3338. /**
  3339. * Set the tags for a post.
  3340. *
  3341. * @since 2.3.0
  3342. *
  3343. * @see wp_set_object_terms()
  3344. *
  3345. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  3346. * @param string $tags Optional. The tags to set for the post, separated by commas.
  3347. * Default empty.
  3348. * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
  3349. * replace the tags with the new tags. Default false.
  3350. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  3351. */
  3352. function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  3353. return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
  3354. }
  3355. /**
  3356. * Set the terms for a post.
  3357. *
  3358. * @since 2.8.0
  3359. *
  3360. * @see wp_set_object_terms()
  3361. *
  3362. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  3363. * @param string $tags Optional. The tags to set for the post, separated by commas. Default empty.
  3364. * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
  3365. * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
  3366. * replace the tags with the new tags. Default false.
  3367. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  3368. */
  3369. function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  3370. $post_id = (int) $post_id;
  3371. if ( !$post_id )
  3372. return false;
  3373. if ( empty($tags) )
  3374. $tags = array();
  3375. if ( ! is_array( $tags ) ) {
  3376. $comma = _x( ',', 'tag delimiter' );
  3377. if ( ',' !== $comma )
  3378. $tags = str_replace( $comma, ',', $tags );
  3379. $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
  3380. }
  3381. /*
  3382. * Hierarchical taxonomies must always pass IDs rather than names so that
  3383. * children with the same names but different parents aren't confused.
  3384. */
  3385. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  3386. $tags = array_unique( array_map( 'intval', $tags ) );
  3387. }
  3388. return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
  3389. }
  3390. /**
  3391. * Set categories for a post.
  3392. *
  3393. * If the post categories parameter is not set, then the default category is
  3394. * going used.
  3395. *
  3396. * @since 2.1.0
  3397. *
  3398. * @param int $post_ID Optional. The Post ID. Does not default to the ID
  3399. * of the global $post. Default 0.
  3400. * @param array|int $post_categories Optional. List of categories or ID of category.
  3401. * Default empty array.
  3402. * @param bool $append If true, don't delete existing categories, just add on.
  3403. * If false, replace the categories with the new categories.
  3404. * @return bool|mixed
  3405. */
  3406. function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
  3407. $post_ID = (int) $post_ID;
  3408. $post_type = get_post_type( $post_ID );
  3409. $post_status = get_post_status( $post_ID );
  3410. // If $post_categories isn't already an array, make it one:
  3411. $post_categories = (array) $post_categories;
  3412. if ( empty( $post_categories ) ) {
  3413. if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
  3414. $post_categories = array( get_option('default_category') );
  3415. $append = false;
  3416. } else {
  3417. $post_categories = array();
  3418. }
  3419. } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
  3420. return true;
  3421. }
  3422. return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
  3423. }
  3424. /**
  3425. * Transition the post status of a post.
  3426. *
  3427. * Calls hooks to transition post status.
  3428. *
  3429. * The first is 'transition_post_status' with new status, old status, and post data.
  3430. *
  3431. * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
  3432. * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
  3433. * post data.
  3434. *
  3435. * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
  3436. * parameter and POSTTYPE is post_type post data.
  3437. *
  3438. * @since 2.3.0
  3439. *
  3440. * @param string $new_status Transition to this post status.
  3441. * @param string $old_status Previous post status.
  3442. * @param WP_Post $post Post data.
  3443. */
  3444. function wp_transition_post_status( $new_status, $old_status, $post ) {
  3445. /**
  3446. * Fires when a post is transitioned from one status to another.
  3447. *
  3448. * @since 2.3.0
  3449. *
  3450. * @param string $new_status New post status.
  3451. * @param string $old_status Old post status.
  3452. * @param WP_Post $post Post object.
  3453. */
  3454. do_action( 'transition_post_status', $new_status, $old_status, $post );
  3455. /**
  3456. * Fires when a post is transitioned from one status to another.
  3457. *
  3458. * The dynamic portions of the hook name, `$new_status` and `$old status`,
  3459. * refer to the old and new post statuses, respectively.
  3460. *
  3461. * @since 2.3.0
  3462. *
  3463. * @param WP_Post $post Post object.
  3464. */
  3465. do_action( "{$old_status}_to_{$new_status}", $post );
  3466. /**
  3467. * Fires when a post is transitioned from one status to another.
  3468. *
  3469. * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
  3470. * refer to the new post status and post type, respectively.
  3471. *
  3472. * @since 2.3.0
  3473. *
  3474. * @param int $post_id Post ID.
  3475. * @param WP_Post $post Post object.
  3476. */
  3477. do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
  3478. }
  3479. //
  3480. // Trackback and ping functions
  3481. //
  3482. /**
  3483. * Add a URL to those already pinged.
  3484. *
  3485. * @since 1.5.0
  3486. *
  3487. * @global wpdb $wpdb WordPress database abstraction object.
  3488. *
  3489. * @param int $post_id Post ID.
  3490. * @param string $uri Ping URI.
  3491. * @return int How many rows were updated.
  3492. */
  3493. function add_ping( $post_id, $uri ) {
  3494. global $wpdb;
  3495. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3496. $pung = trim($pung);
  3497. $pung = preg_split('/\s/', $pung);
  3498. $pung[] = $uri;
  3499. $new = implode("\n", $pung);
  3500. /**
  3501. * Filter the new ping URL to add for the given post.
  3502. *
  3503. * @since 2.0.0
  3504. *
  3505. * @param string $new New ping URL to add.
  3506. */
  3507. $new = apply_filters( 'add_ping', $new );
  3508. // expected_slashed ($new).
  3509. $new = wp_unslash($new);
  3510. return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
  3511. }
  3512. /**
  3513. * Retrieve enclosures already enclosed for a post.
  3514. *
  3515. * @since 1.5.0
  3516. *
  3517. * @param int $post_id Post ID.
  3518. * @return array List of enclosures.
  3519. */
  3520. function get_enclosed( $post_id ) {
  3521. $custom_fields = get_post_custom( $post_id );
  3522. $pung = array();
  3523. if ( !is_array( $custom_fields ) )
  3524. return $pung;
  3525. foreach ( $custom_fields as $key => $val ) {
  3526. if ( 'enclosure' != $key || !is_array( $val ) )
  3527. continue;
  3528. foreach( $val as $enc ) {
  3529. $enclosure = explode( "\n", $enc );
  3530. $pung[] = trim( $enclosure[ 0 ] );
  3531. }
  3532. }
  3533. /**
  3534. * Filter the list of enclosures already enclosed for the given post.
  3535. *
  3536. * @since 2.0.0
  3537. *
  3538. * @param array $pung Array of enclosures for the given post.
  3539. * @param int $post_id Post ID.
  3540. */
  3541. $pung = apply_filters( 'get_enclosed', $pung, $post_id );
  3542. return $pung;
  3543. }
  3544. /**
  3545. * Retrieve URLs already pinged for a post.
  3546. *
  3547. * @since 1.5.0
  3548. *
  3549. * @global wpdb $wpdb WordPress database abstraction object.
  3550. *
  3551. * @param int $post_id Post ID.
  3552. * @return array
  3553. */
  3554. function get_pung( $post_id ) {
  3555. global $wpdb;
  3556. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3557. $pung = trim($pung);
  3558. $pung = preg_split('/\s/', $pung);
  3559. /**
  3560. * Filter the list of already-pinged URLs for the given post.
  3561. *
  3562. * @since 2.0.0
  3563. *
  3564. * @param array $pung Array of URLs already pinged for the given post.
  3565. */
  3566. $pung = apply_filters( 'get_pung', $pung );
  3567. return $pung;
  3568. }
  3569. /**
  3570. * Retrieve URLs that need to be pinged.
  3571. *
  3572. * @since 1.5.0
  3573. *
  3574. * @global wpdb $wpdb WordPress database abstraction object.
  3575. *
  3576. * @param int $post_id Post ID
  3577. * @return array
  3578. */
  3579. function get_to_ping( $post_id ) {
  3580. global $wpdb;
  3581. $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3582. $to_ping = sanitize_trackback_urls( $to_ping );
  3583. $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
  3584. /**
  3585. * Filter the list of URLs yet to ping for the given post.
  3586. *
  3587. * @since 2.0.0
  3588. *
  3589. * @param array $to_ping List of URLs yet to ping.
  3590. */
  3591. $to_ping = apply_filters( 'get_to_ping', $to_ping );
  3592. return $to_ping;
  3593. }
  3594. /**
  3595. * Do trackbacks for a list of URLs.
  3596. *
  3597. * @since 1.0.0
  3598. *
  3599. * @param string $tb_list Comma separated list of URLs.
  3600. * @param int $post_id Post ID.
  3601. */
  3602. function trackback_url_list( $tb_list, $post_id ) {
  3603. if ( ! empty( $tb_list ) ) {
  3604. // Get post data.
  3605. $postdata = get_post( $post_id, ARRAY_A );
  3606. // Form an excerpt.
  3607. $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
  3608. if ( strlen( $excerpt ) > 255 ) {
  3609. $excerpt = substr( $excerpt, 0, 252 ) . '&hellip;';
  3610. }
  3611. $trackback_urls = explode( ',', $tb_list );
  3612. foreach( (array) $trackback_urls as $tb_url ) {
  3613. $tb_url = trim( $tb_url );
  3614. trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
  3615. }
  3616. }
  3617. }
  3618. //
  3619. // Page functions
  3620. //
  3621. /**
  3622. * Get a list of page IDs.
  3623. *
  3624. * @since 2.0.0
  3625. *
  3626. * @global wpdb $wpdb WordPress database abstraction object.
  3627. *
  3628. * @return array List of page IDs.
  3629. */
  3630. function get_all_page_ids() {
  3631. global $wpdb;
  3632. $page_ids = wp_cache_get('all_page_ids', 'posts');
  3633. if ( ! is_array( $page_ids ) ) {
  3634. $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
  3635. wp_cache_add('all_page_ids', $page_ids, 'posts');
  3636. }
  3637. return $page_ids;
  3638. }
  3639. /**
  3640. * Retrieves page data given a page ID or page object.
  3641. *
  3642. * Use get_post() instead of get_page().
  3643. *
  3644. * @since 1.5.1
  3645. * @deprecated 3.5.0 Use get_post()
  3646. *
  3647. * @param mixed $page Page object or page ID. Passed by reference.
  3648. * @param string $output Optional. What to output. Accepts OBJECT, ARRAY_A, or ARRAY_N.
  3649. * Default OBJECT.
  3650. * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
  3651. * 'edit', 'db', 'display'. Default 'raw'.
  3652. * @return WP_Post|null WP_Post on success or null on failure.
  3653. */
  3654. function get_page( $page, $output = OBJECT, $filter = 'raw') {
  3655. return get_post( $page, $output, $filter );
  3656. }
  3657. /**
  3658. * Retrieves a page given its path.
  3659. *
  3660. * @since 2.1.0
  3661. *
  3662. * @global wpdb $wpdb WordPress database abstraction object.
  3663. *
  3664. * @param string $page_path Page path.
  3665. * @param string $output Optional. Output type. Accepts OBJECT, ARRAY_N, or ARRAY_A.
  3666. * Default OBJECT.
  3667. * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
  3668. * @return WP_Post|null WP_Post on success or null on failure.
  3669. */
  3670. function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
  3671. global $wpdb;
  3672. $page_path = rawurlencode(urldecode($page_path));
  3673. $page_path = str_replace('%2F', '/', $page_path);
  3674. $page_path = str_replace('%20', ' ', $page_path);
  3675. $parts = explode( '/', trim( $page_path, '/' ) );
  3676. $parts = esc_sql( $parts );
  3677. $parts = array_map( 'sanitize_title_for_query', $parts );
  3678. $in_string = "'" . implode( "','", $parts ) . "'";
  3679. if ( is_array( $post_type ) ) {
  3680. $post_types = $post_type;
  3681. } else {
  3682. $post_types = array( $post_type, 'attachment' );
  3683. }
  3684. $post_types = esc_sql( $post_types );
  3685. $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
  3686. $sql = "
  3687. SELECT ID, post_name, post_parent, post_type
  3688. FROM $wpdb->posts
  3689. WHERE post_name IN ($in_string)
  3690. AND post_type IN ($post_type_in_string)
  3691. ";
  3692. $pages = $wpdb->get_results( $sql, OBJECT_K );
  3693. $revparts = array_reverse( $parts );
  3694. $foundid = 0;
  3695. foreach ( (array) $pages as $page ) {
  3696. if ( $page->post_name == $revparts[0] ) {
  3697. $count = 0;
  3698. $p = $page;
  3699. while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
  3700. $count++;
  3701. $parent = $pages[ $p->post_parent ];
  3702. if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
  3703. break;
  3704. $p = $parent;
  3705. }
  3706. if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
  3707. $foundid = $page->ID;
  3708. if ( $page->post_type == $post_type )
  3709. break;
  3710. }
  3711. }
  3712. }
  3713. if ( $foundid )
  3714. return get_post( $foundid, $output );
  3715. return null;
  3716. }
  3717. /**
  3718. * Retrieve a page given its title.
  3719. *
  3720. * @since 2.1.0
  3721. *
  3722. * @global wpdb $wpdb WordPress database abstraction object.
  3723. *
  3724. * @param string $page_title Page title
  3725. * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
  3726. * Default OBJECT.
  3727. * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
  3728. * @return WP_Post|null WP_Post on success or null on failure
  3729. */
  3730. function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
  3731. global $wpdb;
  3732. if ( is_array( $post_type ) ) {
  3733. $post_type = esc_sql( $post_type );
  3734. $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
  3735. $sql = $wpdb->prepare( "
  3736. SELECT ID
  3737. FROM $wpdb->posts
  3738. WHERE post_title = %s
  3739. AND post_type IN ($post_type_in_string)
  3740. ", $page_title );
  3741. } else {
  3742. $sql = $wpdb->prepare( "
  3743. SELECT ID
  3744. FROM $wpdb->posts
  3745. WHERE post_title = %s
  3746. AND post_type = %s
  3747. ", $page_title, $post_type );
  3748. }
  3749. $page = $wpdb->get_var( $sql );
  3750. if ( $page )
  3751. return get_post( $page, $output );
  3752. return null;
  3753. }
  3754. /**
  3755. * Retrieve child pages from list of pages matching page ID.
  3756. *
  3757. * Matches against the pages parameter against the page ID. Also matches all
  3758. * children for the same to retrieve all children of a page. Does not make any
  3759. * SQL queries to get the children.
  3760. *
  3761. * @since 1.5.1
  3762. *
  3763. * @param int $page_id Page ID.
  3764. * @param array $pages List of pages' objects.
  3765. * @return array List of page children.
  3766. */
  3767. function get_page_children( $page_id, $pages ) {
  3768. $page_list = array();
  3769. foreach ( (array) $pages as $page ) {
  3770. if ( $page->post_parent == $page_id ) {
  3771. $page_list[] = $page;
  3772. if ( $children = get_page_children( $page->ID, $pages ) ) {
  3773. $page_list = array_merge( $page_list, $children );
  3774. }
  3775. }
  3776. }
  3777. return $page_list;
  3778. }
  3779. /**
  3780. * Order the pages with children under parents in a flat list.
  3781. *
  3782. * It uses auxiliary structure to hold parent-children relationships and
  3783. * runs in O(N) complexity
  3784. *
  3785. * @since 2.0.0
  3786. *
  3787. * @param array $pages Posts array, passed by reference.
  3788. * @param int $page_id Optional. Parent page ID. Default 0.
  3789. * @return array A list arranged by hierarchy. Children immediately follow their parents.
  3790. */
  3791. function get_page_hierarchy( &$pages, $page_id = 0 ) {
  3792. if ( empty( $pages ) ) {
  3793. $result = array();
  3794. return $result;
  3795. }
  3796. $children = array();
  3797. foreach ( (array) $pages as $p ) {
  3798. $parent_id = intval( $p->post_parent );
  3799. $children[ $parent_id ][] = $p;
  3800. }
  3801. $result = array();
  3802. _page_traverse_name( $page_id, $children, $result );
  3803. return $result;
  3804. }
  3805. /**
  3806. * Traverse and return all the nested children post names of a root page.
  3807. *
  3808. * $children contains parent-children relations
  3809. *
  3810. * @since 2.9.0
  3811. *
  3812. * @see _page_traverse_name()
  3813. *
  3814. * @param int $page_id Page ID.
  3815. * @param array &$children Parent-children relations, passed by reference.
  3816. * @param array &$result Result, passed by reference.
  3817. */
  3818. function _page_traverse_name( $page_id, &$children, &$result ){
  3819. if ( isset( $children[ $page_id ] ) ){
  3820. foreach( (array)$children[ $page_id ] as $child ) {
  3821. $result[ $child->ID ] = $child->post_name;
  3822. _page_traverse_name( $child->ID, $children, $result );
  3823. }
  3824. }
  3825. }
  3826. /**
  3827. * Build URI for a page.
  3828. *
  3829. * Sub pages will be in the "directory" under the parent page post name.
  3830. *
  3831. * @since 1.5.0
  3832. *
  3833. * @param WP_Post|object|int $page Page object or page ID.
  3834. * @return string|false Page URI, false on error.
  3835. */
  3836. function get_page_uri( $page ) {
  3837. $page = get_post( $page );
  3838. if ( ! $page )
  3839. return false;
  3840. $uri = $page->post_name;
  3841. foreach ( $page->ancestors as $parent ) {
  3842. $uri = get_post( $parent )->post_name . '/' . $uri;
  3843. }
  3844. return $uri;
  3845. }
  3846. /**
  3847. * Retrieve a list of pages.
  3848. *
  3849. * @global wpdb $wpdb WordPress database abstraction object.
  3850. *
  3851. * @since 1.5.0
  3852. *
  3853. * @param array|string $args {
  3854. * Optional. Array or string of arguments to retrieve pages.
  3855. *
  3856. * @type int $child_of Page ID to return child and grandchild pages of.
  3857. * Default 0, or no restriction.
  3858. * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
  3859. * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author',
  3860. * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
  3861. * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
  3862. * 'post_' can be omitted for any values that start with it.
  3863. * Default 'post_title'.
  3864. * @type bool $hierarchical Whether to return pages hierarchically. Default true.
  3865. * @type array $exclude Array of page IDs to exclude. Default empty array.
  3866. * @type array $include Array of page IDs to include. Cannot be used with `$child_of`,
  3867. * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
  3868. * Default empty array.
  3869. * @type string $meta_key Only include pages with this meta key. Default empty.
  3870. * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`.
  3871. * Default empty.
  3872. * @type string $authors A comma-separated list of author IDs. Default empty.
  3873. * @type int $parent Page ID to return direct children of. `$hierarchical` must be false.
  3874. * Default -1, or no restriction.
  3875. * @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
  3876. * Default empty array.
  3877. * @type int $number The number of pages to return. Default 0, or all pages.
  3878. * @type int $offset The number of pages to skip before returning. Requires `$number`.
  3879. * Default 0.
  3880. * @type string $post_type The post type to query. Default 'page'.
  3881. * @type string $post_status A comma-separated list of post status types to include.
  3882. * Default 'publish'.
  3883. * }
  3884. * @return array List of pages matching defaults or `$args`.
  3885. */
  3886. function get_pages( $args = array() ) {
  3887. global $wpdb;
  3888. $defaults = array(
  3889. 'child_of' => 0, 'sort_order' => 'ASC',
  3890. 'sort_column' => 'post_title', 'hierarchical' => 1,
  3891. 'exclude' => array(), 'include' => array(),
  3892. 'meta_key' => '', 'meta_value' => '',
  3893. 'authors' => '', 'parent' => -1, 'exclude_tree' => array(),
  3894. 'number' => '', 'offset' => 0,
  3895. 'post_type' => 'page', 'post_status' => 'publish',
  3896. );
  3897. $r = wp_parse_args( $args, $defaults );
  3898. $number = (int) $r['number'];
  3899. $offset = (int) $r['offset'];
  3900. $child_of = (int) $r['child_of'];
  3901. $hierarchical = $r['hierarchical'];
  3902. $exclude = $r['exclude'];
  3903. $meta_key = $r['meta_key'];
  3904. $meta_value = $r['meta_value'];
  3905. $parent = $r['parent'];
  3906. $post_status = $r['post_status'];
  3907. // Make sure the post type is hierarchical.
  3908. $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
  3909. if ( ! in_array( $r['post_type'], $hierarchical_post_types ) ) {
  3910. return false;
  3911. }
  3912. if ( $parent > 0 && ! $child_of ) {
  3913. $hierarchical = false;
  3914. }
  3915. // Make sure we have a valid post status.
  3916. if ( ! is_array( $post_status ) ) {
  3917. $post_status = explode( ',', $post_status );
  3918. }
  3919. if ( array_diff( $post_status, get_post_stati() ) ) {
  3920. return false;
  3921. }
  3922. // $args can be whatever, only use the args defined in defaults to compute the key.
  3923. $key = md5( serialize( wp_array_slice_assoc( $r, array_keys( $defaults ) ) ) );
  3924. $last_changed = wp_cache_get( 'last_changed', 'posts' );
  3925. if ( ! $last_changed ) {
  3926. $last_changed = microtime();
  3927. wp_cache_set( 'last_changed', $last_changed, 'posts' );
  3928. }
  3929. $cache_key = "get_pages:$key:$last_changed";
  3930. if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
  3931. // Convert to WP_Post instances.
  3932. $pages = array_map( 'get_post', $cache );
  3933. /** This filter is documented in wp-includes/post.php */
  3934. $pages = apply_filters( 'get_pages', $pages, $r );
  3935. return $pages;
  3936. }
  3937. $inclusions = '';
  3938. if ( ! empty( $r['include'] ) ) {
  3939. $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
  3940. $parent = -1;
  3941. $exclude = '';
  3942. $meta_key = '';
  3943. $meta_value = '';
  3944. $hierarchical = false;
  3945. $incpages = wp_parse_id_list( $r['include'] );
  3946. if ( ! empty( $incpages ) ) {
  3947. $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
  3948. }
  3949. }
  3950. $exclusions = '';
  3951. if ( ! empty( $exclude ) ) {
  3952. $expages = wp_parse_id_list( $exclude );
  3953. if ( ! empty( $expages ) ) {
  3954. $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
  3955. }
  3956. }
  3957. $author_query = '';
  3958. if ( ! empty( $r['authors'] ) ) {
  3959. $post_authors = preg_split( '/[\s,]+/', $r['authors'] );
  3960. if ( ! empty( $post_authors ) ) {
  3961. foreach ( $post_authors as $post_author ) {
  3962. //Do we have an author id or an author login?
  3963. if ( 0 == intval($post_author) ) {
  3964. $post_author = get_user_by('login', $post_author);
  3965. if ( empty( $post_author ) ) {
  3966. continue;
  3967. }
  3968. if ( empty( $post_author->ID ) ) {
  3969. continue;
  3970. }
  3971. $post_author = $post_author->ID;
  3972. }
  3973. if ( '' == $author_query ) {
  3974. $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
  3975. } else {
  3976. $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
  3977. }
  3978. }
  3979. if ( '' != $author_query ) {
  3980. $author_query = " AND ($author_query)";
  3981. }
  3982. }
  3983. }
  3984. $join = '';
  3985. $where = "$exclusions $inclusions ";
  3986. if ( '' !== $meta_key || '' !== $meta_value ) {
  3987. $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
  3988. // meta_key and meta_value might be slashed
  3989. $meta_key = wp_unslash($meta_key);
  3990. $meta_value = wp_unslash($meta_value);
  3991. if ( '' !== $meta_key ) {
  3992. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
  3993. }
  3994. if ( '' !== $meta_value ) {
  3995. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
  3996. }
  3997. }
  3998. if ( is_array( $parent ) ) {
  3999. $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
  4000. if ( ! empty( $post_parent__in ) ) {
  4001. $where .= " AND post_parent IN ($post_parent__in)";
  4002. }
  4003. } elseif ( $parent >= 0 ) {
  4004. $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
  4005. }
  4006. if ( 1 == count( $post_status ) ) {
  4007. $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $r['post_type'], array_shift( $post_status ) );
  4008. } else {
  4009. $post_status = implode( "', '", $post_status );
  4010. $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $r['post_type'] );
  4011. }
  4012. $orderby_array = array();
  4013. $allowed_keys = array( 'author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
  4014. 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
  4015. 'ID', 'rand', 'comment_count' );
  4016. foreach ( explode( ',', $r['sort_column'] ) as $orderby ) {
  4017. $orderby = trim( $orderby );
  4018. if ( ! in_array( $orderby, $allowed_keys ) ) {
  4019. continue;
  4020. }
  4021. switch ( $orderby ) {
  4022. case 'menu_order':
  4023. break;
  4024. case 'ID':
  4025. $orderby = "$wpdb->posts.ID";
  4026. break;
  4027. case 'rand':
  4028. $orderby = 'RAND()';
  4029. break;
  4030. case 'comment_count':
  4031. $orderby = "$wpdb->posts.comment_count";
  4032. break;
  4033. default:
  4034. if ( 0 === strpos( $orderby, 'post_' ) ) {
  4035. $orderby = "$wpdb->posts." . $orderby;
  4036. } else {
  4037. $orderby = "$wpdb->posts.post_" . $orderby;
  4038. }
  4039. }
  4040. $orderby_array[] = $orderby;
  4041. }
  4042. $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
  4043. $sort_order = strtoupper( $r['sort_order'] );
  4044. if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) {
  4045. $sort_order = 'ASC';
  4046. }
  4047. $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
  4048. $query .= $author_query;
  4049. $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
  4050. if ( ! empty( $number ) ) {
  4051. $query .= ' LIMIT ' . $offset . ',' . $number;
  4052. }
  4053. $pages = $wpdb->get_results($query);
  4054. if ( empty($pages) ) {
  4055. /** This filter is documented in wp-includes/post.php */
  4056. $pages = apply_filters( 'get_pages', array(), $r );
  4057. return $pages;
  4058. }
  4059. // Sanitize before caching so it'll only get done once.
  4060. $num_pages = count($pages);
  4061. for ($i = 0; $i < $num_pages; $i++) {
  4062. $pages[$i] = sanitize_post($pages[$i], 'raw');
  4063. }
  4064. // Update cache.
  4065. update_post_cache( $pages );
  4066. if ( $child_of || $hierarchical ) {
  4067. $pages = get_page_children($child_of, $pages);
  4068. }
  4069. if ( ! empty( $r['exclude_tree'] ) ) {
  4070. $exclude = wp_parse_id_list( $r['exclude_tree'] );
  4071. foreach( $exclude as $id ) {
  4072. $children = get_page_children( $id, $pages );
  4073. foreach ( $children as $child ) {
  4074. $exclude[] = $child->ID;
  4075. }
  4076. }
  4077. $num_pages = count( $pages );
  4078. for ( $i = 0; $i < $num_pages; $i++ ) {
  4079. if ( in_array( $pages[$i]->ID, $exclude ) ) {
  4080. unset( $pages[$i] );
  4081. }
  4082. }
  4083. }
  4084. $page_structure = array();
  4085. foreach ( $pages as $page ) {
  4086. $page_structure[] = $page->ID;
  4087. }
  4088. wp_cache_set( $cache_key, $page_structure, 'posts' );
  4089. // Convert to WP_Post instances
  4090. $pages = array_map( 'get_post', $pages );
  4091. /**
  4092. * Filter the retrieved list of pages.
  4093. *
  4094. * @since 2.1.0
  4095. *
  4096. * @param array $pages List of pages to retrieve.
  4097. * @param array $r Array of get_pages() arguments.
  4098. */
  4099. $pages = apply_filters( 'get_pages', $pages, $r );
  4100. return $pages;
  4101. }
  4102. //
  4103. // Attachment functions
  4104. //
  4105. /**
  4106. * Check if the attachment URI is local one and is really an attachment.
  4107. *
  4108. * @since 2.0.0
  4109. *
  4110. * @param string $url URL to check
  4111. * @return bool True on success, false on failure.
  4112. */
  4113. function is_local_attachment($url) {
  4114. if (strpos($url, home_url()) === false)
  4115. return false;
  4116. if (strpos($url, home_url('/?attachment_id=')) !== false)
  4117. return true;
  4118. if ( $id = url_to_postid($url) ) {
  4119. $post = get_post($id);
  4120. if ( 'attachment' == $post->post_type )
  4121. return true;
  4122. }
  4123. return false;
  4124. }
  4125. /**
  4126. * Insert an attachment.
  4127. *
  4128. * If you set the 'ID' in the $args parameter, it will mean that you are
  4129. * updating and attempt to update the attachment. You can also set the
  4130. * attachment name or title by setting the key 'post_name' or 'post_title'.
  4131. *
  4132. * You can set the dates for the attachment manually by setting the 'post_date'
  4133. * and 'post_date_gmt' keys' values.
  4134. *
  4135. * By default, the comments will use the default settings for whether the
  4136. * comments are allowed. You can close them manually or keep them open by
  4137. * setting the value for the 'comment_status' key.
  4138. *
  4139. * @since 2.0.0
  4140. *
  4141. * @see wp_insert_post()
  4142. *
  4143. * @param string|array $args Arguments for inserting an attachment.
  4144. * @param string $file Optional. Filename.
  4145. * @param int $parent Optional. Parent post ID.
  4146. * @return int Attachment ID.
  4147. */
  4148. function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
  4149. $defaults = array(
  4150. 'file' => $file,
  4151. 'post_parent' => 0
  4152. );
  4153. $data = wp_parse_args( $args, $defaults );
  4154. if ( ! empty( $parent ) ) {
  4155. $data['post_parent'] = $parent;
  4156. }
  4157. $data['post_type'] = 'attachment';
  4158. return wp_insert_post( $data );
  4159. }
  4160. /**
  4161. * Trash or delete an attachment.
  4162. *
  4163. * When an attachment is permanently deleted, the file will also be removed.
  4164. * Deletion removes all post meta fields, taxonomy, comments, etc. associated
  4165. * with the attachment (except the main post).
  4166. *
  4167. * The attachment is moved to the trash instead of permanently deleted unless trash
  4168. * for media is disabled, item is already in the trash, or $force_delete is true.
  4169. *
  4170. * @since 2.0.0
  4171. *
  4172. * @global wpdb $wpdb WordPress database abstraction object.
  4173. *
  4174. * @param int $post_id Attachment ID.
  4175. * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
  4176. * Default false.
  4177. * @return mixed False on failure. Post data on success.
  4178. */
  4179. function wp_delete_attachment( $post_id, $force_delete = false ) {
  4180. global $wpdb;
  4181. if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
  4182. return $post;
  4183. if ( 'attachment' != $post->post_type )
  4184. return false;
  4185. if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
  4186. return wp_trash_post( $post_id );
  4187. delete_post_meta($post_id, '_wp_trash_meta_status');
  4188. delete_post_meta($post_id, '_wp_trash_meta_time');
  4189. $meta = wp_get_attachment_metadata( $post_id );
  4190. $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  4191. $file = get_attached_file( $post_id );
  4192. if ( is_multisite() )
  4193. delete_transient( 'dirsize_cache' );
  4194. /**
  4195. * Fires before an attachment is deleted, at the start of wp_delete_attachment().
  4196. *
  4197. * @since 2.0.0
  4198. *
  4199. * @param int $post_id Attachment ID.
  4200. */
  4201. do_action( 'delete_attachment', $post_id );
  4202. wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
  4203. wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
  4204. // Delete all for any posts.
  4205. delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
  4206. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
  4207. foreach ( $comment_ids as $comment_id )
  4208. wp_delete_comment( $comment_id, true );
  4209. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
  4210. foreach ( $post_meta_ids as $mid )
  4211. delete_metadata_by_mid( 'post', $mid );
  4212. /** This action is documented in wp-includes/post.php */
  4213. do_action( 'delete_post', $post_id );
  4214. $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
  4215. if ( ! $result ) {
  4216. return false;
  4217. }
  4218. /** This action is documented in wp-includes/post.php */
  4219. do_action( 'deleted_post', $post_id );
  4220. $uploadpath = wp_upload_dir();
  4221. if ( ! empty($meta['thumb']) ) {
  4222. // Don't delete the thumb if another attachment uses it.
  4223. 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)) ) {
  4224. $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
  4225. /** This filter is documented in wp-admin/custom-header.php */
  4226. $thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
  4227. @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
  4228. }
  4229. }
  4230. // Remove intermediate and backup images if there are any.
  4231. if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
  4232. foreach ( $meta['sizes'] as $size => $sizeinfo ) {
  4233. $intermediate_file = str_replace( basename( $file ), $sizeinfo['file'], $file );
  4234. /** This filter is documented in wp-admin/custom-header.php */
  4235. $intermediate_file = apply_filters( 'wp_delete_file', $intermediate_file );
  4236. @ unlink( path_join( $uploadpath['basedir'], $intermediate_file ) );
  4237. }
  4238. }
  4239. if ( is_array($backup_sizes) ) {
  4240. foreach ( $backup_sizes as $size ) {
  4241. $del_file = path_join( dirname($meta['file']), $size['file'] );
  4242. /** This filter is documented in wp-admin/custom-header.php */
  4243. $del_file = apply_filters( 'wp_delete_file', $del_file );
  4244. @ unlink( path_join($uploadpath['basedir'], $del_file) );
  4245. }
  4246. }
  4247. /** This filter is documented in wp-admin/custom-header.php */
  4248. $file = apply_filters( 'wp_delete_file', $file );
  4249. if ( ! empty($file) )
  4250. @ unlink($file);
  4251. clean_post_cache( $post );
  4252. return $post;
  4253. }
  4254. /**
  4255. * Retrieve attachment meta field for attachment ID.
  4256. *
  4257. * @since 2.1.0
  4258. *
  4259. * @param int $post_id Attachment ID. Default 0.
  4260. * @param bool $unfiltered Optional. If true, filters are not run. Default false.
  4261. * @return string|bool Attachment meta field. False on failure.
  4262. */
  4263. function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
  4264. $post_id = (int) $post_id;
  4265. if ( !$post = get_post( $post_id ) )
  4266. return false;
  4267. $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
  4268. if ( $unfiltered )
  4269. return $data;
  4270. /**
  4271. * Filter the attachment meta data.
  4272. *
  4273. * @since 2.1.0
  4274. *
  4275. * @param array|bool $data Array of meta data for the given attachment, or false
  4276. * if the object does not exist.
  4277. * @param int $post_id Attachment ID.
  4278. */
  4279. return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
  4280. }
  4281. /**
  4282. * Update metadata for an attachment.
  4283. *
  4284. * @since 2.1.0
  4285. *
  4286. * @param int $post_id Attachment ID.
  4287. * @param array $data Attachment data.
  4288. * @return int|bool False if $post is invalid.
  4289. */
  4290. function wp_update_attachment_metadata( $post_id, $data ) {
  4291. $post_id = (int) $post_id;
  4292. if ( !$post = get_post( $post_id ) )
  4293. return false;
  4294. /**
  4295. * Filter the updated attachment meta data.
  4296. *
  4297. * @since 2.1.0
  4298. *
  4299. * @param array $data Array of updated attachment meta data.
  4300. * @param int $post_id Attachment ID.
  4301. */
  4302. if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
  4303. return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
  4304. else
  4305. return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
  4306. }
  4307. /**
  4308. * Retrieve the URL for an attachment.
  4309. *
  4310. * @since 2.1.0
  4311. *
  4312. * @param int $post_id Optional. Attachment ID. Default 0.
  4313. * @return string|bool Attachment URL, otherwise false.
  4314. */
  4315. function wp_get_attachment_url( $post_id = 0 ) {
  4316. $post_id = (int) $post_id;
  4317. if ( !$post = get_post( $post_id ) )
  4318. return false;
  4319. if ( 'attachment' != $post->post_type )
  4320. return false;
  4321. $url = '';
  4322. // Get attached file.
  4323. if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) {
  4324. // Get upload directory.
  4325. if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
  4326. // Check that the upload base exists in the file location.
  4327. if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
  4328. // Replace file location with url location.
  4329. $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
  4330. } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
  4331. $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
  4332. } else {
  4333. // It's a newly-uploaded file, therefore $file is relative to the basedir.
  4334. $url = $uploads['baseurl'] . "/$file";
  4335. }
  4336. }
  4337. }
  4338. /*
  4339. * If any of the above options failed, Fallback on the GUID as used pre-2.7,
  4340. * not recommended to rely upon this.
  4341. */
  4342. if ( empty($url) ) {
  4343. $url = get_the_guid( $post->ID );
  4344. }
  4345. /**
  4346. * Filter the attachment URL.
  4347. *
  4348. * @since 2.1.0
  4349. *
  4350. * @param string $url URL for the given attachment.
  4351. * @param int $post_id Attachment ID.
  4352. */
  4353. $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
  4354. if ( empty( $url ) )
  4355. return false;
  4356. return $url;
  4357. }
  4358. /**
  4359. * Retrieve thumbnail for an attachment.
  4360. *
  4361. * @since 2.1.0
  4362. *
  4363. * @param int $post_id Optional. Attachment ID. Default 0.
  4364. * @return mixed False on failure. Thumbnail file path on success.
  4365. */
  4366. function wp_get_attachment_thumb_file( $post_id = 0 ) {
  4367. $post_id = (int) $post_id;
  4368. if ( !$post = get_post( $post_id ) )
  4369. return false;
  4370. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
  4371. return false;
  4372. $file = get_attached_file( $post->ID );
  4373. if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
  4374. /**
  4375. * Filter the attachment thumbnail file path.
  4376. *
  4377. * @since 2.1.0
  4378. *
  4379. * @param string $thumbfile File path to the attachment thumbnail.
  4380. * @param int $post_id Attachment ID.
  4381. */
  4382. return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
  4383. }
  4384. return false;
  4385. }
  4386. /**
  4387. * Retrieve URL for an attachment thumbnail.
  4388. *
  4389. * @since 2.1.0
  4390. *
  4391. * @param int $post_id Optional. Attachment ID. Default 0.
  4392. * @return string|bool False on failure. Thumbnail URL on success.
  4393. */
  4394. function wp_get_attachment_thumb_url( $post_id = 0 ) {
  4395. $post_id = (int) $post_id;
  4396. if ( !$post = get_post( $post_id ) )
  4397. return false;
  4398. if ( !$url = wp_get_attachment_url( $post->ID ) )
  4399. return false;
  4400. $sized = image_downsize( $post_id, 'thumbnail' );
  4401. if ( $sized )
  4402. return $sized[0];
  4403. if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
  4404. return false;
  4405. $url = str_replace(basename($url), basename($thumb), $url);
  4406. /**
  4407. * Filter the attachment thumbnail URL.
  4408. *
  4409. * @since 2.1.0
  4410. *
  4411. * @param string $url URL for the attachment thumbnail.
  4412. * @param int $post_id Attachment ID.
  4413. */
  4414. return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
  4415. }
  4416. /**
  4417. * Check if the attachment is an image.
  4418. *
  4419. * @since 2.1.0
  4420. *
  4421. * @param int $post_id Optional. Attachment ID. Default 0.
  4422. * @return bool Whether the attachment is an image.
  4423. */
  4424. function wp_attachment_is_image( $post_id = 0 ) {
  4425. $post_id = (int) $post_id;
  4426. if ( !$post = get_post( $post_id ) )
  4427. return false;
  4428. if ( !$file = get_attached_file( $post->ID ) )
  4429. return false;
  4430. $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
  4431. $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
  4432. if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
  4433. return true;
  4434. return false;
  4435. }
  4436. /**
  4437. * Retrieve the icon for a MIME type.
  4438. *
  4439. * @since 2.1.0
  4440. *
  4441. * @param string|int $mime MIME type or attachment ID.
  4442. * @return string|bool Icon, false otherwise.
  4443. */
  4444. function wp_mime_type_icon( $mime = 0 ) {
  4445. if ( !is_numeric($mime) )
  4446. $icon = wp_cache_get("mime_type_icon_$mime");
  4447. $post_id = 0;
  4448. if ( empty($icon) ) {
  4449. $post_mimes = array();
  4450. if ( is_numeric($mime) ) {
  4451. $mime = (int) $mime;
  4452. if ( $post = get_post( $mime ) ) {
  4453. $post_id = (int) $post->ID;
  4454. $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
  4455. if ( !empty($ext) ) {
  4456. $post_mimes[] = $ext;
  4457. if ( $ext_type = wp_ext2type( $ext ) )
  4458. $post_mimes[] = $ext_type;
  4459. }
  4460. $mime = $post->post_mime_type;
  4461. } else {
  4462. $mime = 0;
  4463. }
  4464. } else {
  4465. $post_mimes[] = $mime;
  4466. }
  4467. $icon_files = wp_cache_get('icon_files');
  4468. if ( !is_array($icon_files) ) {
  4469. /**
  4470. * Filter the icon directory path.
  4471. *
  4472. * @since 2.0.0
  4473. *
  4474. * @param string $path Icon directory absolute path.
  4475. */
  4476. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  4477. /**
  4478. * Filter the icon directory URI.
  4479. *
  4480. * @since 2.0.0
  4481. *
  4482. * @param string $uri Icon directory URI.
  4483. */
  4484. $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
  4485. /**
  4486. * Filter the list of icon directory URIs.
  4487. *
  4488. * @since 2.5.0
  4489. *
  4490. * @param array $uris List of icon directory URIs.
  4491. */
  4492. $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
  4493. $icon_files = array();
  4494. while ( $dirs ) {
  4495. $keys = array_keys( $dirs );
  4496. $dir = array_shift( $keys );
  4497. $uri = array_shift($dirs);
  4498. if ( $dh = opendir($dir) ) {
  4499. while ( false !== $file = readdir($dh) ) {
  4500. $file = basename($file);
  4501. if ( substr($file, 0, 1) == '.' )
  4502. continue;
  4503. if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
  4504. if ( is_dir("$dir/$file") )
  4505. $dirs["$dir/$file"] = "$uri/$file";
  4506. continue;
  4507. }
  4508. $icon_files["$dir/$file"] = "$uri/$file";
  4509. }
  4510. closedir($dh);
  4511. }
  4512. }
  4513. wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
  4514. }
  4515. // Icon basename - extension = MIME wildcard.
  4516. foreach ( $icon_files as $file => $uri )
  4517. $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
  4518. if ( ! empty($mime) ) {
  4519. $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
  4520. $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
  4521. $post_mimes[] = str_replace('/', '_', $mime);
  4522. }
  4523. $matches = wp_match_mime_types(array_keys($types), $post_mimes);
  4524. $matches['default'] = array('default');
  4525. foreach ( $matches as $match => $wilds ) {
  4526. if ( isset($types[$wilds[0]])) {
  4527. $icon = $types[$wilds[0]];
  4528. if ( !is_numeric($mime) )
  4529. wp_cache_add("mime_type_icon_$mime", $icon);
  4530. break;
  4531. }
  4532. }
  4533. }
  4534. /**
  4535. * Filter the mime type icon.
  4536. *
  4537. * @since 2.1.0
  4538. *
  4539. * @param string $icon Path to the mime type icon.
  4540. * @param string $mime Mime type.
  4541. * @param int $post_id Attachment ID. Will equal 0 if the function passed
  4542. * the mime type.
  4543. */
  4544. return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
  4545. }
  4546. /**
  4547. * Check for changed slugs for published post objects and save the old slug.
  4548. *
  4549. * The function is used when a post object of any type is updated,
  4550. * by comparing the current and previous post objects.
  4551. *
  4552. * If the slug was changed and not already part of the old slugs then it will be
  4553. * added to the post meta field ('_wp_old_slug') for storing old slugs for that
  4554. * post.
  4555. *
  4556. * The most logically usage of this function is redirecting changed post objects, so
  4557. * that those that linked to an changed post will be redirected to the new post.
  4558. *
  4559. * @since 2.1.0
  4560. *
  4561. * @param int $post_id Post ID.
  4562. * @param WP_Post $post The Post Object
  4563. * @param WP_Post $post_before The Previous Post Object
  4564. * @return int Same as $post_id
  4565. */
  4566. function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
  4567. // Don't bother if it hasnt changed.
  4568. if ( $post->post_name == $post_before->post_name )
  4569. return;
  4570. // We're only concerned with published, non-hierarchical objects.
  4571. if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
  4572. return;
  4573. $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
  4574. // If we haven't added this old slug before, add it now.
  4575. if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
  4576. add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
  4577. // If the new slug was used previously, delete it from the list.
  4578. if ( in_array($post->post_name, $old_slugs) )
  4579. delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
  4580. }
  4581. /**
  4582. * Retrieve the private post SQL based on capability.
  4583. *
  4584. * This function provides a standardized way to appropriately select on the
  4585. * post_status of a post type. The function will return a piece of SQL code
  4586. * that can be added to a WHERE clause; this SQL is constructed to allow all
  4587. * published posts, and all private posts to which the user has access.
  4588. *
  4589. * @since 2.2.0
  4590. *
  4591. * @param string $post_type Post type. Currently only supports 'post' or 'page'.
  4592. * @return string SQL code that can be added to a where clause.
  4593. */
  4594. function get_private_posts_cap_sql( $post_type ) {
  4595. return get_posts_by_author_sql( $post_type, false );
  4596. }
  4597. /**
  4598. * Retrieve the post SQL based on capability, author, and type.
  4599. *
  4600. * @since 3.0.0
  4601. *
  4602. * @see get_private_posts_cap_sql()
  4603. *
  4604. * @param string $post_type Post type.
  4605. * @param bool $full Optional. Returns a full WHERE statement instead of just
  4606. * an 'andalso' term. Default true.
  4607. * @param int $post_author Optional. Query posts having a single author ID. Default null.
  4608. * @param bool $public_only Optional. Only return public posts. Skips cap checks for
  4609. * $current_user. Default false.
  4610. * @return string SQL WHERE code that can be added to a query.
  4611. */
  4612. function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
  4613. global $wpdb;
  4614. // Private posts.
  4615. $post_type_obj = get_post_type_object( $post_type );
  4616. if ( ! $post_type_obj )
  4617. return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
  4618. /**
  4619. * Filter the capability to read private posts for a custom post type
  4620. * when generating SQL for getting posts by author.
  4621. *
  4622. * @since 2.2.0
  4623. * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
  4624. *
  4625. * @param string $cap Capability.
  4626. */
  4627. if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
  4628. $cap = $post_type_obj->cap->read_private_posts;
  4629. }
  4630. if ( $full ) {
  4631. if ( null === $post_author ) {
  4632. $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
  4633. } else {
  4634. $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
  4635. }
  4636. } else {
  4637. $sql = '';
  4638. }
  4639. $sql .= "(post_status = 'publish'";
  4640. // Only need to check the cap if $public_only is false.
  4641. if ( false === $public_only ) {
  4642. if ( current_user_can( $cap ) ) {
  4643. // Does the user have the capability to view private posts? Guess so.
  4644. $sql .= " OR post_status = 'private'";
  4645. } elseif ( is_user_logged_in() ) {
  4646. // Users can view their own private posts.
  4647. $id = get_current_user_id();
  4648. if ( null === $post_author || ! $full ) {
  4649. $sql .= " OR post_status = 'private' AND post_author = $id";
  4650. } elseif ( $id == (int) $post_author ) {
  4651. $sql .= " OR post_status = 'private'";
  4652. } // else none
  4653. } // else none
  4654. }
  4655. $sql .= ')';
  4656. return $sql;
  4657. }
  4658. /**
  4659. * Retrieve the date that the last post was published.
  4660. *
  4661. * The server timezone is the default and is the difference between GMT and
  4662. * server time. The 'blog' value is the date when the last post was posted. The
  4663. * 'gmt' is when the last post was posted in GMT formatted date.
  4664. *
  4665. * @since 0.71
  4666. *
  4667. * @param string $timezone The location to get the time. Accepts 'gmt', 'blog',
  4668. * or 'server'. Default 'server'.
  4669. * @return string The date of the last post.
  4670. */
  4671. function get_lastpostdate( $timezone = 'server' ) {
  4672. /**
  4673. * Filter the date the last post was published.
  4674. *
  4675. * @since 2.3.0
  4676. *
  4677. * @param string $date Date the last post was published. Likely values are 'gmt',
  4678. * 'blog', or 'server'.
  4679. * @param string $timezone Location to use for getting the post published date.
  4680. */
  4681. return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
  4682. }
  4683. /**
  4684. * Get the timestamp of the last time any post was modified.
  4685. *
  4686. * The server timezone is the default and is the difference between GMT and
  4687. * server time. The 'blog' value is just when the last post was modified. The
  4688. * 'gmt' is when the last post was modified in GMT time.
  4689. *
  4690. * @since 1.2.0
  4691. *
  4692. * @param string $timezone Optional. The timezone for the timestamp. Uses the server's internal timezone.
  4693. * Accepts 'server', 'blog', 'gmt'. or 'server'. 'server' uses the server's
  4694. * internal timezone. 'blog' uses the `post_modified` field, which proxies
  4695. * to the timezone set for the site. 'gmt' uses the `post_modified_gmt` field.
  4696. * Default 'server'.
  4697. * @return string The timestamp.
  4698. */
  4699. function get_lastpostmodified( $timezone = 'server' ) {
  4700. $lastpostmodified = _get_last_post_time( $timezone, 'modified' );
  4701. $lastpostdate = get_lastpostdate($timezone);
  4702. if ( $lastpostdate > $lastpostmodified )
  4703. $lastpostmodified = $lastpostdate;
  4704. /**
  4705. * Filter the date the last post was modified.
  4706. *
  4707. * @since 2.3.0
  4708. *
  4709. * @param string $lastpostmodified Date the last post was modified.
  4710. * @param string $timezone Location to use for getting the post modified date.
  4711. * See {@see get_lastpostmodified()} for accepted `$timezone` values.
  4712. */
  4713. return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
  4714. }
  4715. /**
  4716. * Get the timestamp of the last time any post was modified or published.
  4717. *
  4718. * @since 3.1.0
  4719. * @access private
  4720. *
  4721. * @param string $timezone The timezone for the timestamp. See {@see get_lastpostmodified()}
  4722. * for information on accepted values.
  4723. * @param string $field Post field to check. Accepts 'date' or 'modified'.
  4724. * @return string The timestamp.
  4725. */
  4726. function _get_last_post_time( $timezone, $field ) {
  4727. global $wpdb;
  4728. if ( !in_array( $field, array( 'date', 'modified' ) ) )
  4729. return false;
  4730. $timezone = strtolower( $timezone );
  4731. $key = "lastpost{$field}:$timezone";
  4732. $date = wp_cache_get( $key, 'timeinfo' );
  4733. if ( !$date ) {
  4734. $add_seconds_server = date('Z');
  4735. $post_types = get_post_types( array( 'public' => true ) );
  4736. array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
  4737. $post_types = "'" . implode( "', '", $post_types ) . "'";
  4738. switch ( $timezone ) {
  4739. case 'gmt':
  4740. $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");
  4741. break;
  4742. case 'blog':
  4743. $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");
  4744. break;
  4745. case 'server':
  4746. $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");
  4747. break;
  4748. }
  4749. if ( $date )
  4750. wp_cache_set( $key, $date, 'timeinfo' );
  4751. }
  4752. return $date;
  4753. }
  4754. /**
  4755. * Updates posts in cache.
  4756. *
  4757. * @since 1.5.1
  4758. *
  4759. * @param array $posts Array of post objects, passed by reference.
  4760. */
  4761. function update_post_cache( &$posts ) {
  4762. if ( ! $posts )
  4763. return;
  4764. foreach ( $posts as $post )
  4765. wp_cache_add( $post->ID, $post, 'posts' );
  4766. }
  4767. /**
  4768. * Will clean the post in the cache.
  4769. *
  4770. * Cleaning means delete from the cache of the post. Will call to clean the term
  4771. * object cache associated with the post ID.
  4772. *
  4773. * This function not run if $_wp_suspend_cache_invalidation is not empty. See
  4774. * wp_suspend_cache_invalidation().
  4775. *
  4776. * @since 2.0.0
  4777. *
  4778. * @global wpdb $wpdb WordPress database abstraction object.
  4779. *
  4780. * @param int|WP_Post $post Post ID or post object to remove from the cache.
  4781. */
  4782. function clean_post_cache( $post ) {
  4783. global $_wp_suspend_cache_invalidation, $wpdb;
  4784. if ( ! empty( $_wp_suspend_cache_invalidation ) )
  4785. return;
  4786. $post = get_post( $post );
  4787. if ( empty( $post ) )
  4788. return;
  4789. wp_cache_delete( $post->ID, 'posts' );
  4790. wp_cache_delete( $post->ID, 'post_meta' );
  4791. clean_object_term_cache( $post->ID, $post->post_type );
  4792. wp_cache_delete( 'wp_get_archives', 'general' );
  4793. /**
  4794. * Fires immediately after the given post's cache is cleaned.
  4795. *
  4796. * @since 2.5.0
  4797. *
  4798. * @param int $post_id Post ID.
  4799. * @param WP_Post $post Post object.
  4800. */
  4801. do_action( 'clean_post_cache', $post->ID, $post );
  4802. if ( 'page' == $post->post_type ) {
  4803. wp_cache_delete( 'all_page_ids', 'posts' );
  4804. /**
  4805. * Fires immediately after the given page's cache is cleaned.
  4806. *
  4807. * @since 2.5.0
  4808. *
  4809. * @param int $post_id Post ID.
  4810. */
  4811. do_action( 'clean_page_cache', $post->ID );
  4812. }
  4813. wp_cache_set( 'last_changed', microtime(), 'posts' );
  4814. }
  4815. /**
  4816. * Call major cache updating functions for list of Post objects.
  4817. *
  4818. * @since 1.5.0
  4819. *
  4820. * @param array $posts Array of Post objects
  4821. * @param string $post_type Optional. Post type. Default 'post'.
  4822. * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
  4823. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  4824. */
  4825. function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
  4826. // No point in doing all this work if we didn't match any posts.
  4827. if ( !$posts )
  4828. return;
  4829. update_post_cache($posts);
  4830. $post_ids = array();
  4831. foreach ( $posts as $post )
  4832. $post_ids[] = $post->ID;
  4833. if ( ! $post_type )
  4834. $post_type = 'any';
  4835. if ( $update_term_cache ) {
  4836. if ( is_array($post_type) ) {
  4837. $ptypes = $post_type;
  4838. } elseif ( 'any' == $post_type ) {
  4839. // Just use the post_types in the supplied posts.
  4840. foreach ( $posts as $post )
  4841. $ptypes[] = $post->post_type;
  4842. $ptypes = array_unique($ptypes);
  4843. } else {
  4844. $ptypes = array($post_type);
  4845. }
  4846. if ( ! empty($ptypes) )
  4847. update_object_term_cache($post_ids, $ptypes);
  4848. }
  4849. if ( $update_meta_cache )
  4850. update_postmeta_cache($post_ids);
  4851. }
  4852. /**
  4853. * Updates metadata cache for list of post IDs.
  4854. *
  4855. * Performs SQL query to retrieve the metadata for the post IDs and updates the
  4856. * metadata cache for the posts. Therefore, the functions, which call this
  4857. * function, do not need to perform SQL queries on their own.
  4858. *
  4859. * @since 2.1.0
  4860. *
  4861. * @param array $post_ids List of post IDs.
  4862. * @return bool|array Returns false if there is nothing to update or an array
  4863. * of metadata.
  4864. */
  4865. function update_postmeta_cache( $post_ids ) {
  4866. return update_meta_cache('post', $post_ids);
  4867. }
  4868. /**
  4869. * Will clean the attachment in the cache.
  4870. *
  4871. * Cleaning means delete from the cache. Optionally will clean the term
  4872. * object cache associated with the attachment ID.
  4873. *
  4874. * This function will not run if $_wp_suspend_cache_invalidation is not empty.
  4875. *
  4876. * @since 3.0.0
  4877. *
  4878. * @see wp_suspend_cache_invalidation()
  4879. *
  4880. * @param int $id The attachment ID in the cache to clean.
  4881. * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
  4882. */
  4883. function clean_attachment_cache( $id, $clean_terms = false ) {
  4884. global $_wp_suspend_cache_invalidation;
  4885. if ( !empty($_wp_suspend_cache_invalidation) )
  4886. return;
  4887. $id = (int) $id;
  4888. wp_cache_delete($id, 'posts');
  4889. wp_cache_delete($id, 'post_meta');
  4890. if ( $clean_terms )
  4891. clean_object_term_cache($id, 'attachment');
  4892. /**
  4893. * Fires after the given attachment's cache is cleaned.
  4894. *
  4895. * @since 3.0.0
  4896. *
  4897. * @param int $id Attachment ID.
  4898. */
  4899. do_action( 'clean_attachment_cache', $id );
  4900. }
  4901. //
  4902. // Hooks
  4903. //
  4904. /**
  4905. * Hook for managing future post transitions to published.
  4906. *
  4907. * @since 2.3.0
  4908. * @access private
  4909. *
  4910. * @see wp_clear_scheduled_hook()
  4911. * @global wpdb $wpdb WordPress database abstraction object.
  4912. *
  4913. * @param string $new_status New post status.
  4914. * @param string $old_status Previous post status.
  4915. * @param WP_Post $post Post object.
  4916. */
  4917. function _transition_post_status( $new_status, $old_status, $post ) {
  4918. global $wpdb;
  4919. if ( $old_status != 'publish' && $new_status == 'publish' ) {
  4920. // Reset GUID if transitioning to publish and it is empty.
  4921. if ( '' == get_the_guid($post->ID) )
  4922. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
  4923. /**
  4924. * Fires when a post's status is transitioned from private to published.
  4925. *
  4926. * @since 1.5.0
  4927. * @deprecated 2.3.0 Use 'private_to_publish' instead.
  4928. *
  4929. * @param int $post_id Post ID.
  4930. */
  4931. do_action('private_to_published', $post->ID);
  4932. }
  4933. // If published posts changed clear the lastpostmodified cache.
  4934. if ( 'publish' == $new_status || 'publish' == $old_status) {
  4935. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  4936. wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
  4937. wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
  4938. }
  4939. }
  4940. if ( $new_status !== $old_status ) {
  4941. wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
  4942. wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
  4943. }
  4944. // Always clears the hook in case the post status bounced from future to draft.
  4945. wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
  4946. }
  4947. /**
  4948. * Hook used to schedule publication for a post marked for the future.
  4949. *
  4950. * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
  4951. *
  4952. * @since 2.3.0
  4953. * @access private
  4954. *
  4955. * @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
  4956. * as deprecated with _deprecated_argument() as it conflicts with
  4957. * wp_transition_post_status() and the default filter for
  4958. * {@see _future_post_hook()}.
  4959. * @param WP_Post $post Post object.
  4960. */
  4961. function _future_post_hook( $deprecated, $post ) {
  4962. wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
  4963. wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
  4964. }
  4965. /**
  4966. * Hook to schedule pings and enclosures when a post is published.
  4967. *
  4968. * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
  4969. *
  4970. * @since 2.3.0
  4971. * @access private
  4972. *
  4973. * @param int $post_id The ID in the database table of the post being published.
  4974. */
  4975. function _publish_post_hook( $post_id ) {
  4976. if ( defined( 'XMLRPC_REQUEST' ) ) {
  4977. /**
  4978. * Fires when _publish_post_hook() is called during an XML-RPC request.
  4979. *
  4980. * @since 2.1.0
  4981. *
  4982. * @param int $post_id Post ID.
  4983. */
  4984. do_action( 'xmlrpc_publish_post', $post_id );
  4985. }
  4986. if ( defined('WP_IMPORTING') )
  4987. return;
  4988. if ( get_option('default_pingback_flag') )
  4989. add_post_meta( $post_id, '_pingme', '1' );
  4990. add_post_meta( $post_id, '_encloseme', '1' );
  4991. wp_schedule_single_event(time(), 'do_pings');
  4992. }
  4993. /**
  4994. * Return the post's parent's post_ID
  4995. *
  4996. * @since 3.1.0
  4997. *
  4998. * @param int $post_ID
  4999. *
  5000. * @return int|bool Post parent ID, otherwise false.
  5001. */
  5002. function wp_get_post_parent_id( $post_ID ) {
  5003. $post = get_post( $post_ID );
  5004. if ( !$post || is_wp_error( $post ) )
  5005. return false;
  5006. return (int) $post->post_parent;
  5007. }
  5008. /**
  5009. * Check the given subset of the post hierarchy for hierarchy loops.
  5010. *
  5011. * Prevents loops from forming and breaks those that it finds. Attached
  5012. * to the 'wp_insert_post_parent' filter.
  5013. *
  5014. * @since 3.1.0
  5015. *
  5016. * @see wp_find_hierarchy_loop()
  5017. *
  5018. * @param int $post_parent ID of the parent for the post we're checking.
  5019. * @param int $post_ID ID of the post we're checking.
  5020. * @return int The new post_parent for the post, 0 otherwise.
  5021. */
  5022. function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
  5023. // Nothing fancy here - bail.
  5024. if ( !$post_parent )
  5025. return 0;
  5026. // New post can't cause a loop.
  5027. if ( empty( $post_ID ) )
  5028. return $post_parent;
  5029. // Can't be its own parent.
  5030. if ( $post_parent == $post_ID )
  5031. return 0;
  5032. // Now look for larger loops.
  5033. if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
  5034. return $post_parent; // No loop
  5035. // Setting $post_parent to the given value causes a loop.
  5036. if ( isset( $loop[$post_ID] ) )
  5037. return 0;
  5038. // There's a loop, but it doesn't contain $post_ID. Break the loop.
  5039. foreach ( array_keys( $loop ) as $loop_member )
  5040. wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
  5041. return $post_parent;
  5042. }
  5043. /**
  5044. * Set a post thumbnail.
  5045. *
  5046. * @since 3.1.0
  5047. *
  5048. * @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
  5049. * @param int $thumbnail_id Thumbnail to attach.
  5050. * @return bool True on success, false on failure.
  5051. */
  5052. function set_post_thumbnail( $post, $thumbnail_id ) {
  5053. $post = get_post( $post );
  5054. $thumbnail_id = absint( $thumbnail_id );
  5055. if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
  5056. if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
  5057. return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
  5058. else
  5059. return delete_post_meta( $post->ID, '_thumbnail_id' );
  5060. }
  5061. return false;
  5062. }
  5063. /**
  5064. * Remove a post thumbnail.
  5065. *
  5066. * @since 3.3.0
  5067. *
  5068. * @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
  5069. * @return bool True on success, false on failure.
  5070. */
  5071. function delete_post_thumbnail( $post ) {
  5072. $post = get_post( $post );
  5073. if ( $post )
  5074. return delete_post_meta( $post->ID, '_thumbnail_id' );
  5075. return false;
  5076. }
  5077. /**
  5078. * Delete auto-drafts for new posts that are > 7 days old.
  5079. *
  5080. * @since 3.4.0
  5081. *
  5082. * @global wpdb $wpdb WordPress database abstraction object.
  5083. */
  5084. function wp_delete_auto_drafts() {
  5085. global $wpdb;
  5086. // Cleanup old auto-drafts more than 7 days old.
  5087. $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
  5088. foreach ( (array) $old_posts as $delete ) {
  5089. // Force delete.
  5090. wp_delete_post( $delete, true );
  5091. }
  5092. }
  5093. /**
  5094. * Update the custom taxonomies' term counts when a post's status is changed.
  5095. *
  5096. * For example, default posts term counts (for custom taxonomies) don't include
  5097. * private / draft posts.
  5098. *
  5099. * @since 3.3.0
  5100. * @access private
  5101. *
  5102. * @param string $new_status New post status.
  5103. * @param string $old_status Old post status.
  5104. * @param WP_Post $post Post object.
  5105. */
  5106. function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
  5107. // Update counts for the post's terms.
  5108. foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
  5109. $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
  5110. wp_update_term_count( $tt_ids, $taxonomy );
  5111. }
  5112. }
  5113. /**
  5114. * Adds any posts from the given ids to the cache that do not already exist in cache
  5115. *
  5116. * @since 3.4.0
  5117. * @access private
  5118. *
  5119. * @see update_post_caches()
  5120. *
  5121. * @param array $ids ID list
  5122. * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
  5123. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  5124. */
  5125. function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
  5126. global $wpdb;
  5127. $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
  5128. if ( !empty( $non_cached_ids ) ) {
  5129. $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
  5130. update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
  5131. }
  5132. }