PageRenderTime 87ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/APP/wp-includes/post.php

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