PageRenderTime 86ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/post.php

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