PageRenderTime 79ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/post.php

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