PageRenderTime 80ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/wp-includes/post.php

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