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

/Web/wp-includes/post.php

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