PageRenderTime 76ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/post.php

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