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

/htdocs/wp-includes/post.php

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