PageRenderTime 78ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/post.php

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