PageRenderTime 377ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/post.php

https://bitbucket.org/nlyn/mr.-peacocks
PHP | 5298 lines | 2577 code | 727 blank | 1994 comment | 736 complexity | feff727a2a6da9f6e01c084062d8de0f MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. * Post functions and post utility function.
  4. *
  5. * @package WordPress
  6. * @subpackage Post
  7. * @since 1.5.0
  8. */
  9. //
  10. // Post Type Registration
  11. //
  12. /**
  13. * Creates the initial post types when 'init' action is fired.
  14. *
  15. * @since 2.9.0
  16. */
  17. function create_initial_post_types() {
  18. register_post_type( 'post', array(
  19. 'labels' => array(
  20. 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
  21. ),
  22. 'public' => true,
  23. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  24. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  25. 'capability_type' => 'post',
  26. 'map_meta_cap' => true,
  27. 'hierarchical' => false,
  28. 'rewrite' => false,
  29. 'query_var' => false,
  30. '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. ),
  51. 'public' => true,
  52. 'show_ui' => false,
  53. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  54. '_edit_link' => 'media.php?attachment_id=%d', /* internal use only. don't use this when registering your own post type. */
  55. 'capability_type' => 'post',
  56. 'map_meta_cap' => true,
  57. 'hierarchical' => false,
  58. 'rewrite' => false,
  59. 'query_var' => false,
  60. 'show_in_nav_menus' => false,
  61. 'supports' => array( 'comments' ),
  62. ) );
  63. register_post_type( 'revision', array(
  64. 'labels' => array(
  65. 'name' => __( 'Revisions' ),
  66. 'singular_name' => __( 'Revision' ),
  67. ),
  68. 'public' => false,
  69. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  70. '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
  71. 'capability_type' => 'post',
  72. 'map_meta_cap' => true,
  73. 'hierarchical' => false,
  74. 'rewrite' => false,
  75. 'query_var' => false,
  76. 'can_export' => false,
  77. ) );
  78. register_post_type( 'nav_menu_item', array(
  79. 'labels' => array(
  80. 'name' => __( 'Navigation Menu Items' ),
  81. 'singular_name' => __( 'Navigation Menu Item' ),
  82. ),
  83. 'public' => false,
  84. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  85. 'hierarchical' => false,
  86. 'rewrite' => false,
  87. 'query_var' => false,
  88. ) );
  89. register_post_status( 'publish', array(
  90. 'label' => _x( 'Published', 'post' ),
  91. 'public' => true,
  92. '_builtin' => true, /* internal use only. */
  93. 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
  94. ) );
  95. register_post_status( 'future', array(
  96. 'label' => _x( 'Scheduled', 'post' ),
  97. 'protected' => true,
  98. '_builtin' => true, /* internal use only. */
  99. 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
  100. ) );
  101. register_post_status( 'draft', array(
  102. 'label' => _x( 'Draft', 'post' ),
  103. 'protected' => true,
  104. '_builtin' => true, /* internal use only. */
  105. 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
  106. ) );
  107. register_post_status( 'pending', array(
  108. 'label' => _x( 'Pending', 'post' ),
  109. 'protected' => true,
  110. '_builtin' => true, /* internal use only. */
  111. 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
  112. ) );
  113. register_post_status( 'private', array(
  114. 'label' => _x( 'Private', 'post' ),
  115. 'private' => true,
  116. '_builtin' => true, /* internal use only. */
  117. 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
  118. ) );
  119. register_post_status( 'trash', array(
  120. 'label' => _x( 'Trash', 'post' ),
  121. 'internal' => true,
  122. '_builtin' => true, /* internal use only. */
  123. 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
  124. 'show_in_admin_status_list' => true,
  125. ) );
  126. register_post_status( 'auto-draft', array(
  127. 'label' => 'auto-draft',
  128. 'internal' => true,
  129. '_builtin' => true, /* internal use only. */
  130. ) );
  131. register_post_status( 'inherit', array(
  132. 'label' => 'inherit',
  133. 'internal' => true,
  134. '_builtin' => true, /* internal use only. */
  135. 'exclude_from_search' => false,
  136. ) );
  137. }
  138. add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
  139. /**
  140. * Retrieve attached file path based on attachment ID.
  141. *
  142. * You can optionally send it through the 'get_attached_file' filter, but by
  143. * default it will just return the file path unfiltered.
  144. *
  145. * The function works by getting the single post meta name, named
  146. * '_wp_attached_file' and returning it. This is a convenience function to
  147. * prevent looking up the meta name and provide a mechanism for sending the
  148. * attached filename through a filter.
  149. *
  150. * @since 2.0.0
  151. * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
  152. *
  153. * @param int $attachment_id Attachment ID.
  154. * @param bool $unfiltered Whether to apply filters.
  155. * @return string The file path to the attached file.
  156. */
  157. function get_attached_file( $attachment_id, $unfiltered = false ) {
  158. $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
  159. // If the file is relative, prepend upload dir
  160. if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
  161. $file = $uploads['basedir'] . "/$file";
  162. if ( $unfiltered )
  163. return $file;
  164. return apply_filters( 'get_attached_file', $file, $attachment_id );
  165. }
  166. /**
  167. * Update attachment file path based on attachment ID.
  168. *
  169. * Used to update the file path of the attachment, which uses post meta name
  170. * '_wp_attached_file' to store the path of the attachment.
  171. *
  172. * @since 2.1.0
  173. * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
  174. *
  175. * @param int $attachment_id Attachment ID
  176. * @param string $file File path for the attachment
  177. * @return bool False on failure, true on success.
  178. */
  179. function update_attached_file( $attachment_id, $file ) {
  180. if ( !get_post( $attachment_id ) )
  181. return false;
  182. $file = apply_filters( 'update_attached_file', $file, $attachment_id );
  183. $file = _wp_relative_upload_path($file);
  184. return update_post_meta( $attachment_id, '_wp_attached_file', $file );
  185. }
  186. /**
  187. * Return relative path to an uploaded file.
  188. *
  189. * The path is relative to the current upload dir.
  190. *
  191. * @since 2.9.0
  192. * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
  193. *
  194. * @param string $path Full path to the file
  195. * @return string relative path on success, unchanged path on failure.
  196. */
  197. function _wp_relative_upload_path( $path ) {
  198. $new_path = $path;
  199. if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
  200. if ( 0 === strpos($new_path, $uploads['basedir']) ) {
  201. $new_path = str_replace($uploads['basedir'], '', $new_path);
  202. $new_path = ltrim($new_path, '/');
  203. }
  204. }
  205. return apply_filters( '_wp_relative_upload_path', $new_path, $path );
  206. }
  207. /**
  208. * Retrieve all children of the post parent ID.
  209. *
  210. * Normally, without any enhancements, the children would apply to pages. In the
  211. * context of the inner workings of WordPress, pages, posts, and attachments
  212. * share the same table, so therefore the functionality could apply to any one
  213. * of them. It is then noted that while this function does not work on posts, it
  214. * does not mean that it won't work on posts. It is recommended that you know
  215. * what context you wish to retrieve the children of.
  216. *
  217. * Attachments may also be made the child of a post, so if that is an accurate
  218. * statement (which needs to be verified), it would then be possible to get
  219. * all of the attachments for a post. Attachments have since changed since
  220. * version 2.5, so this is most likely unaccurate, but serves generally as an
  221. * example of what is possible.
  222. *
  223. * The arguments listed as defaults are for this function and also of the
  224. * {@link get_posts()} function. The arguments are combined with the
  225. * get_children defaults and are then passed to the {@link get_posts()}
  226. * function, which accepts additional arguments. You can replace the defaults in
  227. * this function, listed below and the additional arguments listed in the
  228. * {@link get_posts()} function.
  229. *
  230. * The 'post_parent' is the most important argument and important attention
  231. * needs to be paid to the $args parameter. If you pass either an object or an
  232. * integer (number), then just the 'post_parent' is grabbed and everything else
  233. * is lost. If you don't specify any arguments, then it is assumed that you are
  234. * in The Loop and the post parent will be grabbed for from the current post.
  235. *
  236. * The 'post_parent' argument is the ID to get the children. The 'numberposts'
  237. * is the amount of posts to retrieve that has a default of '-1', which is
  238. * used to get all of the posts. Giving a number higher than 0 will only
  239. * retrieve that amount of posts.
  240. *
  241. * The 'post_type' and 'post_status' arguments can be used to choose what
  242. * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
  243. * post types are 'post', 'pages', and 'attachments'. The 'post_status'
  244. * argument will accept any post status within the write administration panels.
  245. *
  246. * @see get_posts() Has additional arguments that can be replaced.
  247. * @internal Claims made in the long description might be inaccurate.
  248. *
  249. * @since 2.0.0
  250. *
  251. * @param mixed $args Optional. User defined arguments for replacing the defaults.
  252. * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
  253. * @return array|bool False on failure and the type will be determined by $output parameter.
  254. */
  255. function get_children($args = '', $output = OBJECT) {
  256. $kids = array();
  257. if ( empty( $args ) ) {
  258. if ( isset( $GLOBALS['post'] ) ) {
  259. $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
  260. } else {
  261. return $kids;
  262. }
  263. } elseif ( is_object( $args ) ) {
  264. $args = array('post_parent' => (int) $args->post_parent );
  265. } elseif ( is_numeric( $args ) ) {
  266. $args = array('post_parent' => (int) $args);
  267. }
  268. $defaults = array(
  269. 'numberposts' => -1, 'post_type' => 'any',
  270. 'post_status' => 'any', 'post_parent' => 0,
  271. );
  272. $r = wp_parse_args( $args, $defaults );
  273. $children = get_posts( $r );
  274. if ( !$children )
  275. return $kids;
  276. update_post_cache($children);
  277. foreach ( $children as $key => $child )
  278. $kids[$child->ID] = $children[$key];
  279. if ( $output == OBJECT ) {
  280. return $kids;
  281. } elseif ( $output == ARRAY_A ) {
  282. foreach ( (array) $kids as $kid )
  283. $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
  284. return $weeuns;
  285. } elseif ( $output == ARRAY_N ) {
  286. foreach ( (array) $kids as $kid )
  287. $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
  288. return $babes;
  289. } else {
  290. return $kids;
  291. }
  292. }
  293. /**
  294. * Get extended entry info (<!--more-->).
  295. *
  296. * There should not be any space after the second dash and before the word
  297. * 'more'. There can be text or space(s) after the word 'more', but won't be
  298. * referenced.
  299. *
  300. * The returned array has 'main' and 'extended' keys. Main has the text before
  301. * the <code><!--more--></code>. The 'extended' key has the content after the
  302. * <code><!--more--></code> comment.
  303. *
  304. * @since 1.0.0
  305. *
  306. * @param string $post Post content.
  307. * @return array Post before ('main') and after ('extended').
  308. */
  309. function get_extended($post) {
  310. //Match the new style more links
  311. if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
  312. list($main, $extended) = explode($matches[0], $post, 2);
  313. } else {
  314. $main = $post;
  315. $extended = '';
  316. }
  317. // Strip leading and trailing whitespace
  318. $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
  319. $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
  320. return array('main' => $main, 'extended' => $extended);
  321. }
  322. /**
  323. * Retrieves post data given a post ID or post object.
  324. *
  325. * See {@link sanitize_post()} for optional $filter values. Also, the parameter
  326. * $post, must be given as a variable, since it is passed by reference.
  327. *
  328. * @since 1.5.1
  329. * @uses $wpdb
  330. * @link http://codex.wordpress.org/Function_Reference/get_post
  331. *
  332. * @param int|object $post Post ID or post object.
  333. * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
  334. * @param string $filter Optional, default is raw.
  335. * @return mixed Post data
  336. */
  337. function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
  338. global $wpdb;
  339. $null = null;
  340. if ( empty($post) ) {
  341. if ( isset($GLOBALS['post']) )
  342. $_post = & $GLOBALS['post'];
  343. else
  344. return $null;
  345. } elseif ( is_object($post) && empty($post->filter) ) {
  346. _get_post_ancestors($post);
  347. $_post = sanitize_post($post, 'raw');
  348. wp_cache_add($post->ID, $_post, 'posts');
  349. } else {
  350. if ( is_object($post) )
  351. $post_id = $post->ID;
  352. else
  353. $post_id = $post;
  354. $post_id = (int) $post_id;
  355. if ( ! $_post = wp_cache_get($post_id, 'posts') ) {
  356. $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id));
  357. if ( ! $_post )
  358. return $null;
  359. _get_post_ancestors($_post);
  360. $_post = sanitize_post($_post, 'raw');
  361. wp_cache_add($_post->ID, $_post, 'posts');
  362. }
  363. }
  364. if ($filter != 'raw')
  365. $_post = sanitize_post($_post, $filter);
  366. if ( $output == OBJECT ) {
  367. return $_post;
  368. } elseif ( $output == ARRAY_A ) {
  369. $__post = get_object_vars($_post);
  370. return $__post;
  371. } elseif ( $output == ARRAY_N ) {
  372. $__post = array_values(get_object_vars($_post));
  373. return $__post;
  374. } else {
  375. return $_post;
  376. }
  377. }
  378. /**
  379. * Retrieve ancestors of a post.
  380. *
  381. * @since 2.5.0
  382. *
  383. * @param int|object $post Post ID or post object
  384. * @return array Ancestor IDs or empty array if none are found.
  385. */
  386. function get_post_ancestors($post) {
  387. $post = get_post($post);
  388. if ( !empty($post->ancestors) )
  389. return $post->ancestors;
  390. return array();
  391. }
  392. /**
  393. * Retrieve data from a post field based on Post ID.
  394. *
  395. * Examples of the post field will be, 'post_type', 'post_status', 'content',
  396. * etc and based off of the post object property or key names.
  397. *
  398. * The context values are based off of the taxonomy filter functions and
  399. * supported values are found within those functions.
  400. *
  401. * @since 2.3.0
  402. * @uses sanitize_post_field() See for possible $context values.
  403. *
  404. * @param string $field Post field name
  405. * @param id $post Post ID
  406. * @param string $context Optional. How to filter the field. Default is display.
  407. * @return WP_Error|string Value in post field or WP_Error on failure
  408. */
  409. function get_post_field( $field, $post, $context = 'display' ) {
  410. $post = (int) $post;
  411. $post = get_post( $post );
  412. if ( is_wp_error($post) )
  413. return $post;
  414. if ( !is_object($post) )
  415. return '';
  416. if ( !isset($post->$field) )
  417. return '';
  418. return sanitize_post_field($field, $post->$field, $post->ID, $context);
  419. }
  420. /**
  421. * Retrieve the mime type of an attachment based on the ID.
  422. *
  423. * This function can be used with any post type, but it makes more sense with
  424. * attachments.
  425. *
  426. * @since 2.0.0
  427. *
  428. * @param int $ID Optional. Post ID.
  429. * @return bool|string False on failure or returns the mime type
  430. */
  431. function get_post_mime_type($ID = '') {
  432. $post = & get_post($ID);
  433. if ( is_object($post) )
  434. return $post->post_mime_type;
  435. return false;
  436. }
  437. /**
  438. * Retrieve the format slug for a post
  439. *
  440. * @since 3.1.0
  441. *
  442. * @param int|object $post A post
  443. *
  444. * @return mixed The format if successful. False if no format is set. WP_Error if errors.
  445. */
  446. function get_post_format( $post = null ) {
  447. $post = get_post($post);
  448. if ( ! post_type_supports( $post->post_type, 'post-formats' ) )
  449. return false;
  450. $_format = get_the_terms( $post->ID, 'post_format' );
  451. if ( empty( $_format ) )
  452. return false;
  453. $format = array_shift( $_format );
  454. return ( str_replace('post-format-', '', $format->slug ) );
  455. }
  456. /**
  457. * Check if a post has a particular format
  458. *
  459. * @since 3.1.0
  460. * @uses has_term()
  461. *
  462. * @param string $format The format to check for
  463. * @param object|id $post The post to check. If not supplied, defaults to the current post if used in the loop.
  464. * @return bool True if the post has the format, false otherwise.
  465. */
  466. function has_post_format( $format, $post = null ) {
  467. return has_term('post-format-' . sanitize_key($format), 'post_format', $post);
  468. }
  469. /**
  470. * Assign a format to a post
  471. *
  472. * @since 3.1.0
  473. *
  474. * @param int|object $post The post for which to assign a format
  475. * @param string $format A format to assign. Use an empty string or array to remove all formats from the post.
  476. * @return mixed WP_Error on error. Array of affected term IDs on success.
  477. */
  478. function set_post_format( $post, $format ) {
  479. $post = get_post($post);
  480. if ( empty($post) )
  481. return new WP_Error('invalid_post', __('Invalid post'));
  482. if ( !empty($format) ) {
  483. $format = sanitize_key($format);
  484. if ( 'standard' == $format || !in_array( $format, array_keys( get_post_format_slugs() ) ) )
  485. $format = '';
  486. else
  487. $format = 'post-format-' . $format;
  488. }
  489. return wp_set_post_terms($post->ID, $format, 'post_format');
  490. }
  491. /**
  492. * Retrieve the post status based on the Post ID.
  493. *
  494. * If the post ID is of an attachment, then the parent post status will be given
  495. * instead.
  496. *
  497. * @since 2.0.0
  498. *
  499. * @param int $ID Post ID
  500. * @return string|bool Post status or false on failure.
  501. */
  502. function get_post_status($ID = '') {
  503. $post = get_post($ID);
  504. if ( !is_object($post) )
  505. return false;
  506. if ( 'attachment' == $post->post_type ) {
  507. if ( 'private' == $post->post_status )
  508. return 'private';
  509. // Unattached attachments are assumed to be published
  510. if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
  511. return 'publish';
  512. // Inherit status from the parent
  513. if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
  514. return get_post_status($post->post_parent);
  515. }
  516. return $post->post_status;
  517. }
  518. /**
  519. * Retrieve all of the WordPress supported post statuses.
  520. *
  521. * Posts have a limited set of valid status values, this provides the
  522. * post_status values and descriptions.
  523. *
  524. * @since 2.5.0
  525. *
  526. * @return array List of post statuses.
  527. */
  528. function get_post_statuses( ) {
  529. $status = array(
  530. 'draft' => __('Draft'),
  531. 'pending' => __('Pending Review'),
  532. 'private' => __('Private'),
  533. 'publish' => __('Published')
  534. );
  535. return $status;
  536. }
  537. /**
  538. * Retrieve all of the WordPress support page statuses.
  539. *
  540. * Pages have a limited set of valid status values, this provides the
  541. * post_status values and descriptions.
  542. *
  543. * @since 2.5.0
  544. *
  545. * @return array List of page statuses.
  546. */
  547. function get_page_statuses( ) {
  548. $status = array(
  549. 'draft' => __('Draft'),
  550. 'private' => __('Private'),
  551. 'publish' => __('Published')
  552. );
  553. return $status;
  554. }
  555. /**
  556. * Register a post type. Do not use before init.
  557. *
  558. * A simple function for creating or modifying a post status based on the
  559. * parameters given. The function will accept an array (second optional
  560. * parameter), along with a string for the post status name.
  561. *
  562. *
  563. * Optional $args contents:
  564. *
  565. * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
  566. * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
  567. * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
  568. * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
  569. * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
  570. * listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
  571. *
  572. * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
  573. *
  574. * @package WordPress
  575. * @subpackage Post
  576. * @since 3.0.0
  577. * @uses $wp_post_statuses Inserts new post status object into the list
  578. *
  579. * @param string $post_status Name of the post status.
  580. * @param array|string $args See above description.
  581. */
  582. function register_post_status($post_status, $args = array()) {
  583. global $wp_post_statuses;
  584. if (!is_array($wp_post_statuses))
  585. $wp_post_statuses = array();
  586. // Args prefixed with an underscore are reserved for internal use.
  587. $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);
  588. $args = wp_parse_args($args, $defaults);
  589. $args = (object) $args;
  590. $post_status = sanitize_key($post_status);
  591. $args->name = $post_status;
  592. if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
  593. $args->internal = true;
  594. if ( null === $args->public )
  595. $args->public = false;
  596. if ( null === $args->private )
  597. $args->private = false;
  598. if ( null === $args->protected )
  599. $args->protected = false;
  600. if ( null === $args->internal )
  601. $args->internal = false;
  602. if ( null === $args->publicly_queryable )
  603. $args->publicly_queryable = $args->public;
  604. if ( null === $args->exclude_from_search )
  605. $args->exclude_from_search = $args->internal;
  606. if ( null === $args->show_in_admin_all_list )
  607. $args->show_in_admin_all_list = !$args->internal;
  608. if ( null === $args->show_in_admin_status_list )
  609. $args->show_in_admin_status_list = !$args->internal;
  610. if ( null === $args->single_view_cap )
  611. $args->single_view_cap = $args->public ? '' : 'edit';
  612. if ( false === $args->label )
  613. $args->label = $post_status;
  614. if ( false === $args->label_count )
  615. $args->label_count = array( $args->label, $args->label );
  616. $wp_post_statuses[$post_status] = $args;
  617. return $args;
  618. }
  619. /**
  620. * Retrieve a post status object by name
  621. *
  622. * @package WordPress
  623. * @subpackage Post
  624. * @since 3.0.0
  625. * @uses $wp_post_statuses
  626. * @see register_post_status
  627. * @see get_post_statuses
  628. *
  629. * @param string $post_status The name of a registered post status
  630. * @return object A post status object
  631. */
  632. function get_post_status_object( $post_status ) {
  633. global $wp_post_statuses;
  634. if ( empty($wp_post_statuses[$post_status]) )
  635. return null;
  636. return $wp_post_statuses[$post_status];
  637. }
  638. /**
  639. * Get a list of all registered post status objects.
  640. *
  641. * @package WordPress
  642. * @subpackage Post
  643. * @since 3.0.0
  644. * @uses $wp_post_statuses
  645. * @see register_post_status
  646. * @see get_post_status_object
  647. *
  648. * @param array|string $args An array of key => value arguments to match against the post status objects.
  649. * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
  650. * @param string $operator The logical operation to perform. 'or' means only one element
  651. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  652. * @return array A list of post type names or objects
  653. */
  654. function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
  655. global $wp_post_statuses;
  656. $field = ('names' == $output) ? 'name' : false;
  657. return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
  658. }
  659. /**
  660. * Whether the post type is hierarchical.
  661. *
  662. * A false return value might also mean that the post type does not exist.
  663. *
  664. * @since 3.0.0
  665. * @see get_post_type_object
  666. *
  667. * @param string $post_type Post type name
  668. * @return bool Whether post type is hierarchical.
  669. */
  670. function is_post_type_hierarchical( $post_type ) {
  671. if ( ! post_type_exists( $post_type ) )
  672. return false;
  673. $post_type = get_post_type_object( $post_type );
  674. return $post_type->hierarchical;
  675. }
  676. /**
  677. * Checks if a post type is registered.
  678. *
  679. * @since 3.0.0
  680. * @uses get_post_type_object()
  681. *
  682. * @param string $post_type Post type name
  683. * @return bool Whether post type is registered.
  684. */
  685. function post_type_exists( $post_type ) {
  686. return (bool) get_post_type_object( $post_type );
  687. }
  688. /**
  689. * Retrieve the post type of the current post or of a given post.
  690. *
  691. * @since 2.1.0
  692. *
  693. * @uses $post The Loop current post global
  694. *
  695. * @param mixed $the_post Optional. Post object or post ID.
  696. * @return bool|string post type or false on failure.
  697. */
  698. function get_post_type( $the_post = false ) {
  699. global $post;
  700. if ( false === $the_post )
  701. $the_post = $post;
  702. elseif ( is_numeric($the_post) )
  703. $the_post = get_post($the_post);
  704. if ( is_object($the_post) )
  705. return $the_post->post_type;
  706. return false;
  707. }
  708. /**
  709. * Retrieve a post type object by name
  710. *
  711. * @package WordPress
  712. * @subpackage Post
  713. * @since 3.0.0
  714. * @uses $wp_post_types
  715. * @see register_post_type
  716. * @see get_post_types
  717. *
  718. * @param string $post_type The name of a registered post type
  719. * @return object A post type object
  720. */
  721. function get_post_type_object( $post_type ) {
  722. global $wp_post_types;
  723. if ( empty($wp_post_types[$post_type]) )
  724. return null;
  725. return $wp_post_types[$post_type];
  726. }
  727. /**
  728. * Get a list of all registered post type objects.
  729. *
  730. * @package WordPress
  731. * @subpackage Post
  732. * @since 2.9.0
  733. * @uses $wp_post_types
  734. * @see register_post_type
  735. *
  736. * @param array|string $args An array of key => value arguments to match against the post type objects.
  737. * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
  738. * @param string $operator The logical operation to perform. 'or' means only one element
  739. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  740. * @return array A list of post type names or objects
  741. */
  742. function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
  743. global $wp_post_types;
  744. $field = ('names' == $output) ? 'name' : false;
  745. return wp_filter_object_list($wp_post_types, $args, $operator, $field);
  746. }
  747. /**
  748. * Register a post type. Do not use before init.
  749. *
  750. * A function for creating or modifying a post type based on the
  751. * parameters given. The function will accept an array (second optional
  752. * parameter), along with a string for the post type name.
  753. *
  754. * Optional $args contents:
  755. *
  756. * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
  757. * - description - A short descriptive summary of what the post type is. Defaults to blank.
  758. * - public - Whether posts of this type should be shown in the admin UI. Defaults to false.
  759. * - exclude_from_search - Whether to exclude posts with this post type from search results.
  760. * Defaults to true if the type is not public, false if the type is public.
  761. * - publicly_queryable - Whether post_type queries can be performed from the front page.
  762. * Defaults to whatever public is set as.
  763. * - show_ui - Whether to generate a default UI for managing this post type. Defaults to true
  764. * if the type is public, false if the type is not public.
  765. * - show_in_menu - Where to show the post type in the admin menu. True for a top level menu,
  766. * false for no menu, or can be a top level page like 'tools.php' or 'edit.php?post_type=page'.
  767. * show_ui must be true.
  768. * - menu_position - The position in the menu order the post type should appear. Defaults to the bottom.
  769. * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
  770. * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
  771. * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
  772. * capabilities, e.g. array('story', 'stories').
  773. * - capabilities - Array of capabilities for this post type. By default the capability_type is used
  774. * as a base to construct capabilities. You can see accepted values in {@link get_post_type_capabilities()}.
  775. * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
  776. * - hierarchical - Whether the post type is hierarchical. Defaults to false.
  777. * - supports - An alias for calling add_post_type_support() directly. See {@link add_post_type_support()}
  778. * for documentation. Defaults to none.
  779. * - register_meta_box_cb - Provide a callback function that will be called when setting up the
  780. * meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
  781. * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
  782. * Default is no taxonomies. Taxonomies can be registered later with register_taxonomy() or
  783. * register_taxonomy_for_object_type().
  784. * - labels - An array of labels for this post type. By default post labels are used for non-hierarchical
  785. * types and page labels for hierarchical ones. You can see accepted values in {@link get_post_type_labels()}.
  786. * - permalink_epmask - The default rewrite endpoint bitmasks.
  787. * - has_archive - True to enable post type archives. Will generate the proper rewrite rules if rewrite is enabled.
  788. * - rewrite - false to prevent rewrite. Defaults to true. Use array('slug'=>$slug) to customize permastruct;
  789. * default will use $post_type as slug. Other options include 'with_front', 'feeds', and 'pages'.
  790. * - query_var - false to prevent queries, or string to value of the query var to use for this post type
  791. * - can_export - true allows this post type to be exported.
  792. * - show_in_nav_menus - true makes this post type available for selection in navigation menus.
  793. * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
  794. * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
  795. *
  796. * @since 2.9.0
  797. * @uses $wp_post_types Inserts new post type object into the list
  798. *
  799. * @param string $post_type Name of the post type.
  800. * @param array|string $args See above description.
  801. * @return object|WP_Error the registered post type object, or an error object
  802. */
  803. function register_post_type($post_type, $args = array()) {
  804. global $wp_post_types, $wp_rewrite, $wp;
  805. if ( !is_array($wp_post_types) )
  806. $wp_post_types = array();
  807. // Args prefixed with an underscore are reserved for internal use.
  808. $defaults = array(
  809. 'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null,
  810. 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null,
  811. '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false,
  812. 'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true,
  813. 'supports' => array(), 'register_meta_box_cb' => null,
  814. 'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null,
  815. 'permalink_epmask' => EP_PERMALINK, 'can_export' => true,
  816. 'show_in_nav_menus' => null, 'show_in_menu' => null, 'show_in_admin_bar' => null,
  817. );
  818. $args = wp_parse_args($args, $defaults);
  819. $args = (object) $args;
  820. $post_type = sanitize_key($post_type);
  821. $args->name = $post_type;
  822. if ( strlen( $post_type ) > 20 )
  823. return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
  824. // If not set, default to the setting for public.
  825. if ( null === $args->publicly_queryable )
  826. $args->publicly_queryable = $args->public;
  827. // If not set, default to the setting for public.
  828. if ( null === $args->show_ui )
  829. $args->show_ui = $args->public;
  830. // If not set, default to the setting for show_ui.
  831. if ( null === $args->show_in_menu || ! $args->show_ui )
  832. $args->show_in_menu = $args->show_ui;
  833. // If not set, default to the whether the full UI is shown.
  834. if ( null === $args->show_in_admin_bar )
  835. $args->show_in_admin_bar = true === $args->show_in_menu;
  836. // Whether to show this type in nav-menus.php. Defaults to the setting for public.
  837. if ( null === $args->show_in_nav_menus )
  838. $args->show_in_nav_menus = $args->public;
  839. // If not set, default to true if not public, false if public.
  840. if ( null === $args->exclude_from_search )
  841. $args->exclude_from_search = !$args->public;
  842. // Back compat with quirky handling in version 3.0. #14122
  843. if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
  844. $args->map_meta_cap = true;
  845. if ( null === $args->map_meta_cap )
  846. $args->map_meta_cap = false;
  847. $args->cap = get_post_type_capabilities( $args );
  848. unset($args->capabilities);
  849. if ( is_array( $args->capability_type ) )
  850. $args->capability_type = $args->capability_type[0];
  851. if ( ! empty($args->supports) ) {
  852. add_post_type_support($post_type, $args->supports);
  853. unset($args->supports);
  854. } else {
  855. // Add default features
  856. add_post_type_support($post_type, array('title', 'editor'));
  857. }
  858. if ( false !== $args->query_var && !empty($wp) ) {
  859. if ( true === $args->query_var )
  860. $args->query_var = $post_type;
  861. $args->query_var = sanitize_title_with_dashes($args->query_var);
  862. $wp->add_query_var($args->query_var);
  863. }
  864. if ( false !== $args->rewrite && '' != get_option('permalink_structure') ) {
  865. if ( ! is_array( $args->rewrite ) )
  866. $args->rewrite = array();
  867. if ( empty( $args->rewrite['slug'] ) )
  868. $args->rewrite['slug'] = $post_type;
  869. if ( ! isset( $args->rewrite['with_front'] ) )
  870. $args->rewrite['with_front'] = true;
  871. if ( ! isset( $args->rewrite['pages'] ) )
  872. $args->rewrite['pages'] = true;
  873. if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
  874. $args->rewrite['feeds'] = (bool) $args->has_archive;
  875. if ( $args->hierarchical )
  876. $wp_rewrite->add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
  877. else
  878. $wp_rewrite->add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
  879. if ( $args->has_archive ) {
  880. $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
  881. if ( $args->rewrite['with_front'] )
  882. $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
  883. else
  884. $archive_slug = $wp_rewrite->root . $archive_slug;
  885. $wp_rewrite->add_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
  886. if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
  887. $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
  888. $wp_rewrite->add_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
  889. $wp_rewrite->add_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
  890. }
  891. if ( $args->rewrite['pages'] )
  892. $wp_rewrite->add_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
  893. }
  894. $wp_rewrite->add_permastruct($post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite['with_front'], $args->permalink_epmask);
  895. }
  896. if ( $args->register_meta_box_cb )
  897. add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1);
  898. $args->labels = get_post_type_labels( $args );
  899. $args->label = $args->labels->name;
  900. $wp_post_types[$post_type] = $args;
  901. add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
  902. foreach ( $args->taxonomies as $taxonomy ) {
  903. register_taxonomy_for_object_type( $taxonomy, $post_type );
  904. }
  905. return $args;
  906. }
  907. /**
  908. * Builds an object with all post type capabilities out of a post type object
  909. *
  910. * Post type capabilities use the 'capability_type' argument as a base, if the
  911. * capability is not set in the 'capabilities' argument array or if the
  912. * 'capabilities' argument is not supplied.
  913. *
  914. * The capability_type argument can optionally be registered as an array, with
  915. * the first value being singular and the second plural, e.g. array('story, 'stories')
  916. * Otherwise, an 's' will be added to the value for the plural form. After
  917. * registration, capability_type will always be a string of the singular value.
  918. *
  919. * By default, seven keys are accepted as part of the capabilities array:
  920. *
  921. * - edit_post, read_post, and delete_post are meta capabilities, which are then
  922. * generally mapped to corresponding primitive capabilities depending on the
  923. * context, which would be the post being edited/read/deleted and the user or
  924. * role being checked. Thus these capabilities would generally not be granted
  925. * directly to users or roles.
  926. *
  927. * - edit_posts - Controls whether objects of this post type can be edited.
  928. * - edit_others_posts - Controls whether objects of this type owned by other users
  929. * can be edited. If the post type does not support an author, then this will
  930. * behave like edit_posts.
  931. * - publish_posts - Controls publishing objects of this post type.
  932. * - read_private_posts - Controls whether private objects can be read.
  933. * These four primitive capabilities are checked in core in various locations.
  934. * There are also seven other primitive capabilities which are not referenced
  935. * directly in core, except in map_meta_cap(), which takes the three aforementioned
  936. * meta capabilities and translates them into one or more primitive capabilities
  937. * that must then be checked against the user or role, depending on the context.
  938. *
  939. * - read - Controls whether objects of this post type can be read.
  940. * - delete_posts - Controls whether objects of this post type can be deleted.
  941. * - delete_private_posts - Controls whether private objects can be deleted.
  942. * - delete_published_posts - Controls whether published objects can be deleted.
  943. * - delete_others_posts - Controls whether objects owned by other users can be
  944. * can be deleted. If the post type does not support an author, then this will
  945. * behave like delete_posts.
  946. * - edit_private_posts - Controls whether private objects can be edited.
  947. * - edit_published_posts - Controls whether published objects can be edited.
  948. *
  949. * These additional capabilities are only used in map_meta_cap(). Thus, they are
  950. * only assigned by default if the post type is registered with the 'map_meta_cap'
  951. * argument set to true (default is false).
  952. *
  953. * @see map_meta_cap()
  954. * @since 3.0.0
  955. *
  956. * @param object $args Post type registration arguments
  957. * @return object object with all the capabilities as member variables
  958. */
  959. function get_post_type_capabilities( $args ) {
  960. if ( ! is_array( $args->capability_type ) )
  961. $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
  962. // Singular base for meta capabilities, plural base for primitive capabilities.
  963. list( $singular_base, $plural_base ) = $args->capability_type;
  964. $default_capabilities = array(
  965. // Meta capabilities
  966. 'edit_post' => 'edit_' . $singular_base,
  967. 'read_post' => 'read_' . $singular_base,
  968. 'delete_post' => 'delete_' . $singular_base,
  969. // Primitive capabilities used outside of map_meta_cap():
  970. 'edit_posts' => 'edit_' . $plural_base,
  971. 'edit_others_posts' => 'edit_others_' . $plural_base,
  972. 'publish_posts' => 'publish_' . $plural_base,
  973. 'read_private_posts' => 'read_private_' . $plural_base,
  974. );
  975. // Primitive capabilities used within map_meta_cap():
  976. if ( $args->map_meta_cap ) {
  977. $default_capabilities_for_mapping = array(
  978. 'read' => 'read',
  979. 'delete_posts' => 'delete_' . $plural_base,
  980. 'delete_private_posts' => 'delete_private_' . $plural_base,
  981. 'delete_published_posts' => 'delete_published_' . $plural_base,
  982. 'delete_others_posts' => 'delete_others_' . $plural_base,
  983. 'edit_private_posts' => 'edit_private_' . $plural_base,
  984. 'edit_published_posts' => 'edit_published_' . $plural_base,
  985. );
  986. $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
  987. }
  988. $capabilities = array_merge( $default_capabilities, $args->capabilities );
  989. // Remember meta capabilities for future reference.
  990. if ( $args->map_meta_cap )
  991. _post_type_meta_capabilities( $capabilities );
  992. return (object) $capabilities;
  993. }
  994. /**
  995. * Stores or returns a list of post type meta caps for map_meta_cap().
  996. *
  997. * @since 3.1.0
  998. * @access private
  999. */
  1000. function _post_type_meta_capabilities( $capabilities = null ) {
  1001. static $meta_caps = array();
  1002. if ( null === $capabilities )
  1003. return $meta_caps;
  1004. foreach ( $capabilities as $core => $custom ) {
  1005. if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
  1006. $meta_caps[ $custom ] = $core;
  1007. }
  1008. }
  1009. /**
  1010. * Builds an object with all post type labels out of a post type object
  1011. *
  1012. * Accepted keys of the label array in the post type object:
  1013. * - name - general name for the post type, usually plural. The same and overriden by $post_type_object->label. Default is Posts/Pages
  1014. * - singular_name - name for one object of this post type. Default is Post/Page
  1015. * - 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>
  1016. * - add_new_item - Default is Add New Post/Add New Page
  1017. * - edit_item - Default is Edit Post/Edit Page
  1018. * - new_item - Default is New Post/New Page
  1019. * - view_item - Default is View Post/View Page
  1020. * - search_items - Default is Search Posts/Search Pages
  1021. * - not_found - Default is No posts found/No pages found
  1022. * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
  1023. * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
  1024. *
  1025. * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
  1026. *
  1027. * @since 3.0.0
  1028. * @param object $post_type_object
  1029. * @return object object with all the labels as member variables
  1030. */
  1031. function get_post_type_labels( $post_type_object ) {
  1032. $nohier_vs_hier_defaults = array(
  1033. 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
  1034. 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
  1035. 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
  1036. 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
  1037. 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
  1038. 'new_item' => array( __('New Post'), __('New Page') ),
  1039. 'view_item' => array( __('View Post'), __('View Page') ),
  1040. 'search_items' => array( __('Search Posts'), __('Search Pages') ),
  1041. 'not_found' => array( __('No posts found.'), __('No pages found.') ),
  1042. 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
  1043. 'parent_item_colon' => array( null, __('Parent Page:') ),
  1044. 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
  1045. );
  1046. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  1047. return _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
  1048. }
  1049. /**
  1050. * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
  1051. *
  1052. * @access private
  1053. * @since 3.0.0
  1054. */
  1055. function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
  1056. if ( isset( $object->label ) && empty( $object->labels['name'] ) )
  1057. $object->labels['name'] = $object->label;
  1058. if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
  1059. $object->labels['singular_name'] = $object->labels['name'];
  1060. if ( ! isset( $object->labels['name_admin_bar'] ) )
  1061. $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
  1062. if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
  1063. $object->labels['menu_name'] = $object->labels['name'];
  1064. if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
  1065. $object->labels['all_items'] = $object->labels['menu_name'];
  1066. foreach ( $nohier_vs_hier_defaults as $key => $value )
  1067. $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
  1068. $labels = array_merge( $defaults, $object->labels );
  1069. return (object)$labels;
  1070. }
  1071. /**
  1072. * Adds submenus for post types.
  1073. *
  1074. * @access private
  1075. * @since 3.1.0
  1076. */
  1077. function _add_post_type_submenus() {
  1078. foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
  1079. $ptype_obj = get_post_type_object( $ptype );
  1080. // Submenus only.
  1081. if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
  1082. continue;
  1083. 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" );
  1084. }
  1085. }
  1086. add_action( 'admin_menu', '_add_post_type_submenus' );
  1087. /**
  1088. * Register support of certain features for a post type.
  1089. *
  1090. * All features are directly associated with a functional area of the edit screen, such as the
  1091. * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
  1092. * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
  1093. *
  1094. * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
  1095. * and the 'comments' feature dicates whether the comments count will show on the edit screen.
  1096. *
  1097. * @since 3.0.0
  1098. * @param string $post_type The post type for which to add the feature
  1099. * @param string|array $feature the feature being added, can be an array of feature strings or a single string
  1100. */
  1101. function add_post_type_support( $post_type, $feature ) {
  1102. global $_wp_post_type_features;
  1103. $features = (array) $feature;
  1104. foreach ($features as $feature) {
  1105. if ( func_num_args() == 2 )
  1106. $_wp_post_type_features[$post_type][$feature] = true;
  1107. else
  1108. $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
  1109. }
  1110. }
  1111. /**
  1112. * Remove support for a feature from a post type.
  1113. *
  1114. * @since 3.0.0
  1115. * @param string $post_type The post type for which to remove the feature
  1116. * @param string $feature The feature being removed
  1117. */
  1118. function remove_post_type_support( $post_type, $feature ) {
  1119. global $_wp_post_type_features;
  1120. if ( !isset($_wp_post_type_features[$post_type]) )
  1121. return;
  1122. if ( isset($_wp_post_type_features[$post_type][$feature]) )
  1123. unset($_wp_post_type_features[$post_type][$feature]);
  1124. }
  1125. /**
  1126. * Checks a post type's support for a given feature
  1127. *
  1128. * @since 3.0.0
  1129. * @param string $post_type The post type being checked
  1130. * @param string $feature the feature being checked
  1131. * @return boolean
  1132. */
  1133. function post_type_supports( $post_type, $feature ) {
  1134. global $_wp_post_type_features;
  1135. if ( !isset( $_wp_post_type_features[$post_type][$feature] ) )
  1136. return false;
  1137. // If no args passed then no extra checks need be performed
  1138. if ( func_num_args() <= 2 )
  1139. return true;
  1140. // @todo Allow pluggable arg checking
  1141. //$args = array_slice( func_get_args(), 2 );
  1142. return true;
  1143. }
  1144. /**
  1145. * Updates the post type for the post ID.
  1146. *
  1147. * The page or post cache will be cleaned for the post ID.
  1148. *
  1149. * @since 2.5.0
  1150. *
  1151. * @uses $wpdb
  1152. *
  1153. * @param int $post_id Post ID to change post type. Not actually optional.
  1154. * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
  1155. * name a few.
  1156. * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
  1157. */
  1158. function set_post_type( $post_id = 0, $post_type = 'post' ) {
  1159. global $wpdb;
  1160. $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
  1161. $return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
  1162. if ( 'page' == $post_type )
  1163. clean_page_cache($post_id);
  1164. else
  1165. clean_post_cache($post_id);
  1166. return $return;
  1167. }
  1168. /**
  1169. * Retrieve list of latest posts or posts matching criteria.
  1170. *
  1171. * The defaults are as follows:
  1172. * 'numberposts' - Default is 5. Total number of posts to retrieve.
  1173. * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
  1174. * 'category' - What category to pull the posts from.
  1175. * 'orderby' - Default is 'post_date'. How to order the posts.
  1176. * 'order' - Default is 'DESC'. The order to retrieve the posts.
  1177. * 'include' - See {@link WP_Query::query()} for more.
  1178. * 'exclude' - See {@link WP_Query::query()} for more.
  1179. * 'meta_key' - See {@link WP_Query::query()} for more.
  1180. * 'meta_value' - See {@link WP_Query::query()} for more.
  1181. * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
  1182. * 'post_parent' - The parent of the post or post type.
  1183. * 'post_status' - Default is 'publish'. Post status to retrieve.
  1184. *
  1185. * @since 1.2.0
  1186. * @uses $wpdb
  1187. * @uses WP_Query::query() See for more default arguments and information.
  1188. * @link http://codex.wordpress.org/Template_Tags/get_posts
  1189. *
  1190. * @param array $args Optional. Overrides defaults.
  1191. * @return array List of posts.
  1192. */
  1193. function get_posts($args = null) {
  1194. $defaults = array(
  1195. 'numberposts' => 5, 'offset' => 0,
  1196. 'category' => 0, 'orderby' => 'post_date',
  1197. 'order' => 'DESC', 'include' => array(),
  1198. 'exclude' => array(), 'meta_key' => '',
  1199. 'meta_value' =>'', 'post_type' => 'post',
  1200. 'suppress_filters' => true
  1201. );
  1202. $r = wp_parse_args( $args, $defaults );
  1203. if ( empty( $r['post_status'] ) )
  1204. $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
  1205. if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
  1206. $r['posts_per_page'] = $r['numberposts'];
  1207. if ( ! empty($r['category']) )
  1208. $r['cat'] = $r['category'];
  1209. if ( ! empty($r['include']) ) {
  1210. $incposts = wp_parse_id_list( $r['include'] );
  1211. $r['posts_per_page'] = count($incposts); // only the number of posts included
  1212. $r['post__in'] = $incposts;
  1213. } elseif ( ! empty($r['exclude']) )
  1214. $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
  1215. $r['ignore_sticky_posts'] = true;
  1216. $r['no_found_rows'] = true;
  1217. $get_posts = new WP_Query;
  1218. return $get_posts->query($r);
  1219. }
  1220. //
  1221. // Post meta functions
  1222. //
  1223. /**
  1224. * Add meta data field to a post.
  1225. *
  1226. * Post meta data is called "Custom Fields" on the Administration Screen.
  1227. *
  1228. * @since 1.5.0
  1229. * @uses $wpdb
  1230. * @link http://codex.wordpress.org/Function_Reference/add_post_meta
  1231. *
  1232. * @param int $post_id Post ID.
  1233. * @param string $meta_key Metadata name.
  1234. * @param mixed $meta_value Metadata value.
  1235. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  1236. * @return bool False for failure. True for success.
  1237. */
  1238. function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
  1239. // make sure meta is added to the post, not a revision
  1240. if ( $the_post = wp_is_post_revision($post_id) )
  1241. $post_id = $the_post;
  1242. return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
  1243. }
  1244. /**
  1245. * Remove metadata matching criteria from a post.
  1246. *
  1247. * You can match based on the key, or key and value. Removing based on key and
  1248. * value, will keep from removing duplicate metadata with the same key. It also
  1249. * allows removing all metadata matching key, if needed.
  1250. *
  1251. * @since 1.5.0
  1252. * @uses $wpdb
  1253. * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
  1254. *
  1255. * @param int $post_id post ID
  1256. * @param string $meta_key Metadata name.
  1257. * @param mixed $meta_value Optional. Metadata value.
  1258. * @return bool False for failure. True for success.
  1259. */
  1260. function delete_post_meta($post_id, $meta_key, $meta_value = '') {
  1261. // make sure meta is added to the post, not a revision
  1262. if ( $the_post = wp_is_post_revision($post_id) )
  1263. $post_id = $the_post;
  1264. return delete_metadata('post', $post_id, $meta_key, $meta_value);
  1265. }
  1266. /**
  1267. * Retrieve post meta field for a post.
  1268. *
  1269. * @since 1.5.0
  1270. * @uses $wpdb
  1271. * @link http://codex.wordpress.org/Function_Reference/get_post_meta
  1272. *
  1273. * @param int $post_id Post ID.
  1274. * @param string $key The meta key to retrieve.
  1275. * @param bool $single Whether to return a single value.
  1276. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  1277. * is true.
  1278. */
  1279. function get_post_meta($post_id, $key, $single = false) {
  1280. return get_metadata('post', $post_id, $key, $single);
  1281. }
  1282. /**
  1283. * Update post meta field based on post ID.
  1284. *
  1285. * Use the $prev_value parameter to differentiate between meta fields with the
  1286. * same key and post ID.
  1287. *
  1288. * If the meta field for the post does not exist, it will be added.
  1289. *
  1290. * @since 1.5.0
  1291. * @uses $wpdb
  1292. * @link http://codex.wordpress.org/Function_Reference/update_post_meta
  1293. *
  1294. * @param int $post_id Post ID.
  1295. * @param string $meta_key Metadata key.
  1296. * @param mixed $meta_value Metadata value.
  1297. * @param mixed $prev_value Optional. Previous value to check before removing.
  1298. * @return bool False on failure, true if success.
  1299. */
  1300. function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
  1301. // make sure meta is added to the post, not a revision
  1302. if ( $the_post = wp_is_post_revision($post_id) )
  1303. $post_id = $the_post;
  1304. return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
  1305. }
  1306. /**
  1307. * Delete everything from post meta matching meta key.
  1308. *
  1309. * @since 2.3.0
  1310. * @uses $wpdb
  1311. *
  1312. * @param string $post_meta_key Key to search for when deleting.
  1313. * @return bool Whether the post meta key was deleted from the database
  1314. */
  1315. function delete_post_meta_by_key($post_meta_key) {
  1316. if ( !$post_meta_key )
  1317. return false;
  1318. global $wpdb;
  1319. $post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
  1320. if ( $post_ids ) {
  1321. $postmetaids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key ) );
  1322. $in = implode( ',', array_fill(1, count($postmetaids), '%d'));
  1323. do_action( 'delete_postmeta', $postmetaids );
  1324. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN($in)", $postmetaids ));
  1325. do_action( 'deleted_postmeta', $postmetaids );
  1326. foreach ( $post_ids as $post_id )
  1327. wp_cache_delete($post_id, 'post_meta');
  1328. return true;
  1329. }
  1330. return false;
  1331. }
  1332. /**
  1333. * Retrieve post meta fields, based on post ID.
  1334. *
  1335. * The post meta fields are retrieved from the cache, so the function is
  1336. * optimized to be called more than once. It also applies to the functions, that
  1337. * use this function.
  1338. *
  1339. * @since 1.2.0
  1340. * @link http://codex.wordpress.org/Function_Reference/get_post_custom
  1341. *
  1342. * @uses $id Current Loop Post ID
  1343. *
  1344. * @param int $post_id post ID
  1345. * @return array
  1346. */
  1347. function get_post_custom( $post_id = 0 ) {
  1348. $post_id = absint( $post_id );
  1349. if ( ! $post_id )
  1350. $post_id = get_the_ID();
  1351. if ( ! wp_cache_get( $post_id, 'post_meta' ) )
  1352. update_postmeta_cache( $post_id );
  1353. return wp_cache_get( $post_id, 'post_meta' );
  1354. }
  1355. /**
  1356. * Retrieve meta field names for a post.
  1357. *
  1358. * If there are no meta fields, then nothing (null) will be returned.
  1359. *
  1360. * @since 1.2.0
  1361. * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
  1362. *
  1363. * @param int $post_id post ID
  1364. * @return array|null Either array of the keys, or null if keys could not be retrieved.
  1365. */
  1366. function get_post_custom_keys( $post_id = 0 ) {
  1367. $custom = get_post_custom( $post_id );
  1368. if ( !is_array($custom) )
  1369. return;
  1370. if ( $keys = array_keys($custom) )
  1371. return $keys;
  1372. }
  1373. /**
  1374. * Retrieve values for a custom post field.
  1375. *
  1376. * The parameters must not be considered optional. All of the post meta fields
  1377. * will be retrieved and only the meta field key values returned.
  1378. *
  1379. * @since 1.2.0
  1380. * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
  1381. *
  1382. * @param string $key Meta field key.
  1383. * @param int $post_id Post ID
  1384. * @return array Meta field values.
  1385. */
  1386. function get_post_custom_values( $key = '', $post_id = 0 ) {
  1387. if ( !$key )
  1388. return null;
  1389. $custom = get_post_custom($post_id);
  1390. return isset($custom[$key]) ? $custom[$key] : null;
  1391. }
  1392. /**
  1393. * Check if post is sticky.
  1394. *
  1395. * Sticky posts should remain at the top of The Loop. If the post ID is not
  1396. * given, then The Loop ID for the current post will be used.
  1397. *
  1398. * @since 2.7.0
  1399. *
  1400. * @param int $post_id Optional. Post ID.
  1401. * @return bool Whether post is sticky.
  1402. */
  1403. function is_sticky( $post_id = 0 ) {
  1404. $post_id = absint( $post_id );
  1405. if ( ! $post_id )
  1406. $post_id = get_the_ID();
  1407. $stickies = get_option( 'sticky_posts' );
  1408. if ( ! is_array( $stickies ) )
  1409. return false;
  1410. if ( in_array( $post_id, $stickies ) )
  1411. return true;
  1412. return false;
  1413. }
  1414. /**
  1415. * Sanitize every post field.
  1416. *
  1417. * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
  1418. *
  1419. * @since 2.3.0
  1420. * @uses sanitize_post_field() Used to sanitize the fields.
  1421. *
  1422. * @param object|array $post The Post Object or Array
  1423. * @param string $context Optional, default is 'display'. How to sanitize post fields.
  1424. * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
  1425. */
  1426. function sanitize_post($post, $context = 'display') {
  1427. if ( is_object($post) ) {
  1428. // Check if post already filtered for this context
  1429. if ( isset($post->filter) && $context == $post->filter )
  1430. return $post;
  1431. if ( !isset($post->ID) )
  1432. $post->ID = 0;
  1433. foreach ( array_keys(get_object_vars($post)) as $field )
  1434. $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
  1435. $post->filter = $context;
  1436. } else {
  1437. // Check if post already filtered for this context
  1438. if ( isset($post['filter']) && $context == $post['filter'] )
  1439. return $post;
  1440. if ( !isset($post['ID']) )
  1441. $post['ID'] = 0;
  1442. foreach ( array_keys($post) as $field )
  1443. $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
  1444. $post['filter'] = $context;
  1445. }
  1446. return $post;
  1447. }
  1448. /**
  1449. * Sanitize post field based on context.
  1450. *
  1451. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1452. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1453. * when calling filters.
  1454. *
  1455. * @since 2.3.0
  1456. * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
  1457. * $post_id if $context == 'edit' and field name prefix == 'post_'.
  1458. *
  1459. * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
  1460. * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
  1461. * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
  1462. *
  1463. * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
  1464. * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
  1465. * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
  1466. * 'edit' and 'db' and field name prefix != 'post_'.
  1467. *
  1468. * @param string $field The Post Object field name.
  1469. * @param mixed $value The Post Object value.
  1470. * @param int $post_id Post ID.
  1471. * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
  1472. * 'attribute' and 'js'.
  1473. * @return mixed Sanitized value.
  1474. */
  1475. function sanitize_post_field($field, $value, $post_id, $context) {
  1476. $int_fields = array('ID', 'post_parent', 'menu_order');
  1477. if ( in_array($field, $int_fields) )
  1478. $value = (int) $value;
  1479. // Fields which contain arrays of ints.
  1480. $array_int_fields = array( 'ancestors' );
  1481. if ( in_array($field, $array_int_fields) ) {
  1482. $value = array_map( 'absint', $value);
  1483. return $value;
  1484. }
  1485. if ( 'raw' == $context )
  1486. return $value;
  1487. $prefixed = false;
  1488. if ( false !== strpos($field, 'post_') ) {
  1489. $prefixed = true;
  1490. $field_no_prefix = str_replace('post_', '', $field);
  1491. }
  1492. if ( 'edit' == $context ) {
  1493. $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
  1494. if ( $prefixed ) {
  1495. $value = apply_filters("edit_{$field}", $value, $post_id);
  1496. // Old school
  1497. $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
  1498. } else {
  1499. $value = apply_filters("edit_post_{$field}", $value, $post_id);
  1500. }
  1501. if ( in_array($field, $format_to_edit) ) {
  1502. if ( 'post_content' == $field )
  1503. $value = format_to_edit($value, user_can_richedit());
  1504. else
  1505. $value = format_to_edit($value);
  1506. } else {
  1507. $value = esc_attr($value);
  1508. }
  1509. } else if ( 'db' == $context ) {
  1510. if ( $prefixed ) {
  1511. $value = apply_filters("pre_{$field}", $value);
  1512. $value = apply_filters("{$field_no_prefix}_save_pre", $value);
  1513. } else {
  1514. $value = apply_filters("pre_post_{$field}", $value);
  1515. $value = apply_filters("{$field}_pre", $value);
  1516. }
  1517. } else {
  1518. // Use display filters by default.
  1519. if ( $prefixed )
  1520. $value = apply_filters($field, $value, $post_id, $context);
  1521. else
  1522. $value = apply_filters("post_{$field}", $value, $post_id, $context);
  1523. }
  1524. if ( 'attribute' == $context )
  1525. $value = esc_attr($value);
  1526. else if ( 'js' == $context )
  1527. $value = esc_js($value);
  1528. return $value;
  1529. }
  1530. /**
  1531. * Make a post sticky.
  1532. *
  1533. * Sticky posts should be displayed at the top of the front page.
  1534. *
  1535. * @since 2.7.0
  1536. *
  1537. * @param int $post_id Post ID.
  1538. */
  1539. function stick_post($post_id) {
  1540. $stickies = get_option('sticky_posts');
  1541. if ( !is_array($stickies) )
  1542. $stickies = array($post_id);
  1543. if ( ! in_array($post_id, $stickies) )
  1544. $stickies[] = $post_id;
  1545. update_option('sticky_posts', $stickies);
  1546. }
  1547. /**
  1548. * Unstick a post.
  1549. *
  1550. * Sticky posts should be displayed at the top of the front page.
  1551. *
  1552. * @since 2.7.0
  1553. *
  1554. * @param int $post_id Post ID.
  1555. */
  1556. function unstick_post($post_id) {
  1557. $stickies = get_option('sticky_posts');
  1558. if ( !is_array($stickies) )
  1559. return;
  1560. if ( ! in_array($post_id, $stickies) )
  1561. return;
  1562. $offset = array_search($post_id, $stickies);
  1563. if ( false === $offset )
  1564. return;
  1565. array_splice($stickies, $offset, 1);
  1566. update_option('sticky_posts', $stickies);
  1567. }
  1568. /**
  1569. * Count number of posts of a post type and is user has permissions to view.
  1570. *
  1571. * This function provides an efficient method of finding the amount of post's
  1572. * type a blog has. Another method is to count the amount of items in
  1573. * get_posts(), but that method has a lot of overhead with doing so. Therefore,
  1574. * when developing for 2.5+, use this function instead.
  1575. *
  1576. * The $perm parameter checks for 'readable' value and if the user can read
  1577. * private posts, it will display that for the user that is signed in.
  1578. *
  1579. * @since 2.5.0
  1580. * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
  1581. *
  1582. * @param string $type Optional. Post type to retrieve count
  1583. * @param string $perm Optional. 'readable' or empty.
  1584. * @return object Number of posts for each status
  1585. */
  1586. function wp_count_posts( $type = 'post', $perm = '' ) {
  1587. global $wpdb;
  1588. $user = wp_get_current_user();
  1589. $cache_key = $type;
  1590. $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
  1591. if ( 'readable' == $perm && is_user_logged_in() ) {
  1592. $post_type_object = get_post_type_object($type);
  1593. if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
  1594. $cache_key .= '_' . $perm . '_' . $user->ID;
  1595. $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
  1596. }
  1597. }
  1598. $query .= ' GROUP BY post_status';
  1599. $count = wp_cache_get($cache_key, 'counts');
  1600. if ( false !== $count )
  1601. return $count;
  1602. $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
  1603. $stats = array();
  1604. foreach ( get_post_stati() as $state )
  1605. $stats[$state] = 0;
  1606. foreach ( (array) $count as $row )
  1607. $stats[$row['post_status']] = $row['num_posts'];
  1608. $stats = (object) $stats;
  1609. wp_cache_set($cache_key, $stats, 'counts');
  1610. return $stats;
  1611. }
  1612. /**
  1613. * Count number of attachments for the mime type(s).
  1614. *
  1615. * If you set the optional mime_type parameter, then an array will still be
  1616. * returned, but will only have the item you are looking for. It does not give
  1617. * you the number of attachments that are children of a post. You can get that
  1618. * by counting the number of children that post has.
  1619. *
  1620. * @since 2.5.0
  1621. *
  1622. * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
  1623. * @return array Number of posts for each mime type.
  1624. */
  1625. function wp_count_attachments( $mime_type = '' ) {
  1626. global $wpdb;
  1627. $and = wp_post_mime_type_where( $mime_type );
  1628. $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 );
  1629. $stats = array( );
  1630. foreach( (array) $count as $row ) {
  1631. $stats[$row['post_mime_type']] = $row['num_posts'];
  1632. }
  1633. $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
  1634. return (object) $stats;
  1635. }
  1636. /**
  1637. * Check a MIME-Type against a list.
  1638. *
  1639. * If the wildcard_mime_types parameter is a string, it must be comma separated
  1640. * list. If the real_mime_types is a string, it is also comma separated to
  1641. * create the list.
  1642. *
  1643. * @since 2.5.0
  1644. *
  1645. * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
  1646. * flash (same as *flash*).
  1647. * @param string|array $real_mime_types post_mime_type values
  1648. * @return array array(wildcard=>array(real types))
  1649. */
  1650. function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
  1651. $matches = array();
  1652. if ( is_string($wildcard_mime_types) )
  1653. $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
  1654. if ( is_string($real_mime_types) )
  1655. $real_mime_types = array_map('trim', explode(',', $real_mime_types));
  1656. $wild = '[-._a-z0-9]*';
  1657. foreach ( (array) $wildcard_mime_types as $type ) {
  1658. $type = str_replace('*', $wild, $type);
  1659. $patternses[1][$type] = "^$type$";
  1660. if ( false === strpos($type, '/') ) {
  1661. $patternses[2][$type] = "^$type/";
  1662. $patternses[3][$type] = $type;
  1663. }
  1664. }
  1665. asort($patternses);
  1666. foreach ( $patternses as $patterns )
  1667. foreach ( $patterns as $type => $pattern )
  1668. foreach ( (array) $real_mime_types as $real )
  1669. if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
  1670. $matches[$type][] = $real;
  1671. return $matches;
  1672. }
  1673. /**
  1674. * Convert MIME types into SQL.
  1675. *
  1676. * @since 2.5.0
  1677. *
  1678. * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
  1679. * @param string $table_alias Optional. Specify a table alias, if needed.
  1680. * @return string The SQL AND clause for mime searching.
  1681. */
  1682. function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
  1683. $where = '';
  1684. $wildcards = array('', '%', '%/%');
  1685. if ( is_string($post_mime_types) )
  1686. $post_mime_types = array_map('trim', explode(',', $post_mime_types));
  1687. foreach ( (array) $post_mime_types as $mime_type ) {
  1688. $mime_type = preg_replace('/\s/', '', $mime_type);
  1689. $slashpos = strpos($mime_type, '/');
  1690. if ( false !== $slashpos ) {
  1691. $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
  1692. $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
  1693. if ( empty($mime_subgroup) )
  1694. $mime_subgroup = '*';
  1695. else
  1696. $mime_subgroup = str_replace('/', '', $mime_subgroup);
  1697. $mime_pattern = "$mime_group/$mime_subgroup";
  1698. } else {
  1699. $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
  1700. if ( false === strpos($mime_pattern, '*') )
  1701. $mime_pattern .= '/*';
  1702. }
  1703. $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
  1704. if ( in_array( $mime_type, $wildcards ) )
  1705. return '';
  1706. if ( false !== strpos($mime_pattern, '%') )
  1707. $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
  1708. else
  1709. $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
  1710. }
  1711. if ( !empty($wheres) )
  1712. $where = ' AND (' . join(' OR ', $wheres) . ') ';
  1713. return $where;
  1714. }
  1715. /**
  1716. * Trashes or deletes a post or page.
  1717. *
  1718. * When the post and page is permanently deleted, everything that is tied to it is deleted also.
  1719. * This includes comments, post meta fields, and terms associated with the post.
  1720. *
  1721. * The post or page is moved to trash instead of permanently deleted unless trash is
  1722. * disabled, item is already in the trash, or $force_delete is true.
  1723. *
  1724. * @since 1.0.0
  1725. * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
  1726. * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
  1727. * @uses wp_delete_attachment() if post type is 'attachment'.
  1728. * @uses wp_trash_post() if item should be trashed.
  1729. *
  1730. * @param int $postid Post ID.
  1731. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  1732. * @return mixed False on failure
  1733. */
  1734. function wp_delete_post( $postid = 0, $force_delete = false ) {
  1735. global $wpdb, $wp_rewrite;
  1736. if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
  1737. return $post;
  1738. if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
  1739. return wp_trash_post($postid);
  1740. if ( $post->post_type == 'attachment' )
  1741. return wp_delete_attachment( $postid, $force_delete );
  1742. do_action('before_delete_post', $postid);
  1743. delete_post_meta($postid,'_wp_trash_meta_status');
  1744. delete_post_meta($postid,'_wp_trash_meta_time');
  1745. wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
  1746. $parent_data = array( 'post_parent' => $post->post_parent );
  1747. $parent_where = array( 'post_parent' => $postid );
  1748. if ( 'page' == $post->post_type) {
  1749. // if the page is defined in option page_on_front or post_for_posts,
  1750. // adjust the corresponding options
  1751. if ( get_option('page_on_front') == $postid ) {
  1752. update_option('show_on_front', 'posts');
  1753. delete_option('page_on_front');
  1754. }
  1755. if ( get_option('page_for_posts') == $postid ) {
  1756. delete_option('page_for_posts');
  1757. }
  1758. // Point children of this page to its parent, also clean the cache of affected children
  1759. $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
  1760. $children = $wpdb->get_results($children_query);
  1761. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
  1762. } else {
  1763. unstick_post($postid);
  1764. }
  1765. // Do raw query. wp_get_post_revisions() is filtered
  1766. $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
  1767. // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
  1768. foreach ( $revision_ids as $revision_id )
  1769. wp_delete_post_revision( $revision_id );
  1770. // Point all attachments to this post up one level
  1771. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
  1772. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
  1773. if ( ! empty($comment_ids) ) {
  1774. do_action( 'delete_comment', $comment_ids );
  1775. foreach ( $comment_ids as $comment_id )
  1776. wp_delete_comment( $comment_id, true );
  1777. do_action( 'deleted_comment', $comment_ids );
  1778. }
  1779. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
  1780. if ( !empty($post_meta_ids) ) {
  1781. do_action( 'delete_postmeta', $post_meta_ids );
  1782. $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
  1783. $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
  1784. do_action( 'deleted_postmeta', $post_meta_ids );
  1785. }
  1786. do_action( 'delete_post', $postid );
  1787. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
  1788. do_action( 'deleted_post', $postid );
  1789. if ( 'page' == $post->post_type ) {
  1790. clean_page_cache($postid);
  1791. foreach ( (array) $children as $child )
  1792. clean_page_cache($child->ID);
  1793. $wp_rewrite->flush_rules(false);
  1794. } else {
  1795. clean_post_cache($postid);
  1796. }
  1797. wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
  1798. do_action('after_delete_post', $postid);
  1799. return $post;
  1800. }
  1801. /**
  1802. * Moves a post or page to the Trash
  1803. *
  1804. * If trash is disabled, the post or page is permanently deleted.
  1805. *
  1806. * @since 2.9.0
  1807. * @uses do_action() on 'trash_post' before trashing
  1808. * @uses do_action() on 'trashed_post' after trashing
  1809. * @uses wp_delete_post() if trash is disabled
  1810. *
  1811. * @param int $post_id Post ID.
  1812. * @return mixed False on failure
  1813. */
  1814. function wp_trash_post($post_id = 0) {
  1815. if ( !EMPTY_TRASH_DAYS )
  1816. return wp_delete_post($post_id, true);
  1817. if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1818. return $post;
  1819. if ( $post['post_status'] == 'trash' )
  1820. return false;
  1821. do_action('trash_post', $post_id);
  1822. add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
  1823. add_post_meta($post_id,'_wp_trash_meta_time', time());
  1824. $post['post_status'] = 'trash';
  1825. wp_insert_post($post);
  1826. wp_trash_post_comments($post_id);
  1827. do_action('trashed_post', $post_id);
  1828. return $post;
  1829. }
  1830. /**
  1831. * Restores a post or page from the Trash
  1832. *
  1833. * @since 2.9.0
  1834. * @uses do_action() on 'untrash_post' before undeletion
  1835. * @uses do_action() on 'untrashed_post' after undeletion
  1836. *
  1837. * @param int $post_id Post ID.
  1838. * @return mixed False on failure
  1839. */
  1840. function wp_untrash_post($post_id = 0) {
  1841. if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1842. return $post;
  1843. if ( $post['post_status'] != 'trash' )
  1844. return false;
  1845. do_action('untrash_post', $post_id);
  1846. $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
  1847. $post['post_status'] = $post_status;
  1848. delete_post_meta($post_id, '_wp_trash_meta_status');
  1849. delete_post_meta($post_id, '_wp_trash_meta_time');
  1850. wp_insert_post($post);
  1851. wp_untrash_post_comments($post_id);
  1852. do_action('untrashed_post', $post_id);
  1853. return $post;
  1854. }
  1855. /**
  1856. * Moves comments for a post to the trash
  1857. *
  1858. * @since 2.9.0
  1859. * @uses do_action() on 'trash_post_comments' before trashing
  1860. * @uses do_action() on 'trashed_post_comments' after trashing
  1861. *
  1862. * @param int $post Post ID or object.
  1863. * @return mixed False on failure
  1864. */
  1865. function wp_trash_post_comments($post = null) {
  1866. global $wpdb;
  1867. $post = get_post($post);
  1868. if ( empty($post) )
  1869. return;
  1870. $post_id = $post->ID;
  1871. do_action('trash_post_comments', $post_id);
  1872. $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
  1873. if ( empty($comments) )
  1874. return;
  1875. // Cache current status for each comment
  1876. $statuses = array();
  1877. foreach ( $comments as $comment )
  1878. $statuses[$comment->comment_ID] = $comment->comment_approved;
  1879. add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
  1880. // Set status for all comments to post-trashed
  1881. $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
  1882. clean_comment_cache( array_keys($statuses) );
  1883. do_action('trashed_post_comments', $post_id, $statuses);
  1884. return $result;
  1885. }
  1886. /**
  1887. * Restore comments for a post from the trash
  1888. *
  1889. * @since 2.9.0
  1890. * @uses do_action() on 'untrash_post_comments' before trashing
  1891. * @uses do_action() on 'untrashed_post_comments' after trashing
  1892. *
  1893. * @param int $post Post ID or object.
  1894. * @return mixed False on failure
  1895. */
  1896. function wp_untrash_post_comments($post = null) {
  1897. global $wpdb;
  1898. $post = get_post($post);
  1899. if ( empty($post) )
  1900. return;
  1901. $post_id = $post->ID;
  1902. $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
  1903. if ( empty($statuses) )
  1904. return true;
  1905. do_action('untrash_post_comments', $post_id);
  1906. // Restore each comment to its original status
  1907. $group_by_status = array();
  1908. foreach ( $statuses as $comment_id => $comment_status )
  1909. $group_by_status[$comment_status][] = $comment_id;
  1910. foreach ( $group_by_status as $status => $comments ) {
  1911. // Sanity check. This shouldn't happen.
  1912. if ( 'post-trashed' == $status )
  1913. $status = '0';
  1914. $comments_in = implode( "', '", $comments );
  1915. $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" );
  1916. }
  1917. clean_comment_cache( array_keys($statuses) );
  1918. delete_post_meta($post_id, '_wp_trash_meta_comments_status');
  1919. do_action('untrashed_post_comments', $post_id);
  1920. }
  1921. /**
  1922. * Retrieve the list of categories for a post.
  1923. *
  1924. * Compatibility layer for themes and plugins. Also an easy layer of abstraction
  1925. * away from the complexity of the taxonomy layer.
  1926. *
  1927. * @since 2.1.0
  1928. *
  1929. * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
  1930. *
  1931. * @param int $post_id Optional. The Post ID.
  1932. * @param array $args Optional. Overwrite the defaults.
  1933. * @return array
  1934. */
  1935. function wp_get_post_categories( $post_id = 0, $args = array() ) {
  1936. $post_id = (int) $post_id;
  1937. $defaults = array('fields' => 'ids');
  1938. $args = wp_parse_args( $args, $defaults );
  1939. $cats = wp_get_object_terms($post_id, 'category', $args);
  1940. return $cats;
  1941. }
  1942. /**
  1943. * Retrieve the tags for a post.
  1944. *
  1945. * There is only one default for this function, called 'fields' and by default
  1946. * is set to 'all'. There are other defaults that can be overridden in
  1947. * {@link wp_get_object_terms()}.
  1948. *
  1949. * @package WordPress
  1950. * @subpackage Post
  1951. * @since 2.3.0
  1952. *
  1953. * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
  1954. *
  1955. * @param int $post_id Optional. The Post ID
  1956. * @param array $args Optional. Overwrite the defaults
  1957. * @return array List of post tags.
  1958. */
  1959. function wp_get_post_tags( $post_id = 0, $args = array() ) {
  1960. return wp_get_post_terms( $post_id, 'post_tag', $args);
  1961. }
  1962. /**
  1963. * Retrieve the terms for a post.
  1964. *
  1965. * There is only one default for this function, called 'fields' and by default
  1966. * is set to 'all'. There are other defaults that can be overridden in
  1967. * {@link wp_get_object_terms()}.
  1968. *
  1969. * @package WordPress
  1970. * @subpackage Post
  1971. * @since 2.8.0
  1972. *
  1973. * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
  1974. *
  1975. * @param int $post_id Optional. The Post ID
  1976. * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
  1977. * @param array $args Optional. Overwrite the defaults
  1978. * @return array List of post tags.
  1979. */
  1980. function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
  1981. $post_id = (int) $post_id;
  1982. $defaults = array('fields' => 'all');
  1983. $args = wp_parse_args( $args, $defaults );
  1984. $tags = wp_get_object_terms($post_id, $taxonomy, $args);
  1985. return $tags;
  1986. }
  1987. /**
  1988. * Retrieve number of recent posts.
  1989. *
  1990. * @since 1.0.0
  1991. * @uses wp_parse_args()
  1992. * @uses get_posts()
  1993. *
  1994. * @param string $deprecated Deprecated.
  1995. * @param array $args Optional. Overrides defaults.
  1996. * @param string $output Optional.
  1997. * @return unknown.
  1998. */
  1999. function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
  2000. if ( is_numeric( $args ) ) {
  2001. _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  2002. $args = array( 'numberposts' => absint( $args ) );
  2003. }
  2004. // Set default arguments
  2005. $defaults = array(
  2006. 'numberposts' => 10, 'offset' => 0,
  2007. 'category' => 0, 'orderby' => 'post_date',
  2008. 'order' => 'DESC', 'include' => '',
  2009. 'exclude' => '', 'meta_key' => '',
  2010. 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
  2011. 'suppress_filters' => true
  2012. );
  2013. $r = wp_parse_args( $args, $defaults );
  2014. $results = get_posts( $r );
  2015. // Backward compatibility. Prior to 3.1 expected posts to be returned in array
  2016. if ( ARRAY_A == $output ){
  2017. foreach( $results as $key => $result ) {
  2018. $results[$key] = get_object_vars( $result );
  2019. }
  2020. return $results ? $results : array();
  2021. }
  2022. return $results ? $results : false;
  2023. }
  2024. /**
  2025. * Retrieve a single post, based on post ID.
  2026. *
  2027. * Has categories in 'post_category' property or key. Has tags in 'tags_input'
  2028. * property or key.
  2029. *
  2030. * @since 1.0.0
  2031. *
  2032. * @param int $postid Post ID.
  2033. * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
  2034. * @return object|array Post object or array holding post contents and information
  2035. */
  2036. function wp_get_single_post($postid = 0, $mode = OBJECT) {
  2037. $postid = (int) $postid;
  2038. $post = get_post($postid, $mode);
  2039. if (
  2040. ( OBJECT == $mode && empty( $post->ID ) ) ||
  2041. ( OBJECT != $mode && empty( $post['ID'] ) )
  2042. )
  2043. return ( OBJECT == $mode ? null : array() );
  2044. // Set categories and tags
  2045. if ( $mode == OBJECT ) {
  2046. $post->post_category = array();
  2047. if ( is_object_in_taxonomy($post->post_type, 'category') )
  2048. $post->post_category = wp_get_post_categories($postid);
  2049. $post->tags_input = array();
  2050. if ( is_object_in_taxonomy($post->post_type, 'post_tag') )
  2051. $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
  2052. } else {
  2053. $post['post_category'] = array();
  2054. if ( is_object_in_taxonomy($post['post_type'], 'category') )
  2055. $post['post_category'] = wp_get_post_categories($postid);
  2056. $post['tags_input'] = array();
  2057. if ( is_object_in_taxonomy($post['post_type'], 'post_tag') )
  2058. $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
  2059. }
  2060. return $post;
  2061. }
  2062. /**
  2063. * Insert a post.
  2064. *
  2065. * If the $postarr parameter has 'ID' set to a value, then post will be updated.
  2066. *
  2067. * You can set the post date manually, but setting the values for 'post_date'
  2068. * and 'post_date_gmt' keys. You can close the comments or open the comments by
  2069. * setting the value for 'comment_status' key.
  2070. *
  2071. * The defaults for the parameter $postarr are:
  2072. * 'post_status' - Default is 'draft'.
  2073. * 'post_type' - Default is 'post'.
  2074. * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
  2075. * 'ping_status' - Default is the value in 'default_ping_status' option.
  2076. * Whether the attachment can accept pings.
  2077. * 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
  2078. * 'menu_order' - Default is 0. The order it is displayed.
  2079. * 'to_ping' - Whether to ping.
  2080. * 'pinged' - Default is empty string.
  2081. * 'post_password' - Default is empty string. The password to access the attachment.
  2082. * 'guid' - Global Unique ID for referencing the attachment.
  2083. * 'post_content_filtered' - Post content filtered.
  2084. * 'post_excerpt' - Post excerpt.
  2085. *
  2086. * @since 1.0.0
  2087. * @uses $wpdb
  2088. * @uses $wp_rewrite
  2089. * @uses $user_ID
  2090. * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
  2091. * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
  2092. * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
  2093. * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
  2094. * @uses wp_transition_post_status()
  2095. *
  2096. * @param array $postarr Elements that make up post to insert.
  2097. * @param bool $wp_error Optional. Allow return of WP_Error on failure.
  2098. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  2099. */
  2100. function wp_insert_post($postarr, $wp_error = false) {
  2101. global $wpdb, $wp_rewrite, $user_ID;
  2102. $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  2103. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  2104. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  2105. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
  2106. 'post_content' => '', 'post_title' => '');
  2107. $postarr = wp_parse_args($postarr, $defaults);
  2108. unset( $postarr[ 'filter' ] );
  2109. $postarr = sanitize_post($postarr, 'db');
  2110. // export array as variables
  2111. extract($postarr, EXTR_SKIP);
  2112. // Are we updating or creating?
  2113. $update = false;
  2114. if ( !empty($ID) ) {
  2115. $update = true;
  2116. $previous_status = get_post_field('post_status', $ID);
  2117. } else {
  2118. $previous_status = 'new';
  2119. }
  2120. if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
  2121. if ( $wp_error )
  2122. return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
  2123. else
  2124. return 0;
  2125. }
  2126. if ( empty($post_type) )
  2127. $post_type = 'post';
  2128. if ( empty($post_status) )
  2129. $post_status = 'draft';
  2130. if ( !empty($post_category) )
  2131. $post_category = array_filter($post_category); // Filter out empty terms
  2132. // Make sure we set a valid category.
  2133. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  2134. // 'post' requires at least one category.
  2135. if ( 'post' == $post_type && 'auto-draft' != $post_status )
  2136. $post_category = array( get_option('default_category') );
  2137. else
  2138. $post_category = array();
  2139. }
  2140. if ( empty($post_author) )
  2141. $post_author = $user_ID;
  2142. $post_ID = 0;
  2143. // Get the post ID and GUID
  2144. if ( $update ) {
  2145. $post_ID = (int) $ID;
  2146. $guid = get_post_field( 'guid', $post_ID );
  2147. $post_before = get_post($post_ID);
  2148. }
  2149. // Don't allow contributors to set the post slug for pending review posts
  2150. if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
  2151. $post_name = '';
  2152. // Create a valid post name. Drafts and pending posts are allowed to have an empty
  2153. // post name.
  2154. if ( empty($post_name) ) {
  2155. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2156. $post_name = sanitize_title($post_title);
  2157. else
  2158. $post_name = '';
  2159. } else {
  2160. $post_name = sanitize_title($post_name);
  2161. }
  2162. // 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
  2163. if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
  2164. $post_date = current_time('mysql');
  2165. if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
  2166. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2167. $post_date_gmt = get_gmt_from_date($post_date);
  2168. else
  2169. $post_date_gmt = '0000-00-00 00:00:00';
  2170. }
  2171. if ( $update || '0000-00-00 00:00:00' == $post_date ) {
  2172. $post_modified = current_time( 'mysql' );
  2173. $post_modified_gmt = current_time( 'mysql', 1 );
  2174. } else {
  2175. $post_modified = $post_date;
  2176. $post_modified_gmt = $post_date_gmt;
  2177. }
  2178. if ( 'publish' == $post_status ) {
  2179. $now = gmdate('Y-m-d H:i:59');
  2180. if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
  2181. $post_status = 'future';
  2182. } elseif( 'future' == $post_status ) {
  2183. $now = gmdate('Y-m-d H:i:59');
  2184. if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
  2185. $post_status = 'publish';
  2186. }
  2187. if ( empty($comment_status) ) {
  2188. if ( $update )
  2189. $comment_status = 'closed';
  2190. else
  2191. $comment_status = get_option('default_comment_status');
  2192. }
  2193. if ( empty($ping_status) )
  2194. $ping_status = get_option('default_ping_status');
  2195. if ( isset($to_ping) )
  2196. $to_ping = preg_replace('|\s+|', "\n", $to_ping);
  2197. else
  2198. $to_ping = '';
  2199. if ( ! isset($pinged) )
  2200. $pinged = '';
  2201. if ( isset($post_parent) )
  2202. $post_parent = (int) $post_parent;
  2203. else
  2204. $post_parent = 0;
  2205. // Check the post_parent to see if it will cause a hierarchy loop
  2206. $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
  2207. if ( isset($menu_order) )
  2208. $menu_order = (int) $menu_order;
  2209. else
  2210. $menu_order = 0;
  2211. if ( !isset($post_password) || 'private' == $post_status )
  2212. $post_password = '';
  2213. $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
  2214. // expected_slashed (everything!)
  2215. $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' ) );
  2216. $data = apply_filters('wp_insert_post_data', $data, $postarr);
  2217. $data = stripslashes_deep( $data );
  2218. $where = array( 'ID' => $post_ID );
  2219. if ( $update ) {
  2220. do_action( 'pre_post_update', $post_ID );
  2221. if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  2222. if ( $wp_error )
  2223. return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  2224. else
  2225. return 0;
  2226. }
  2227. } else {
  2228. if ( isset($post_mime_type) )
  2229. $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
  2230. // If there is a suggested ID, use it if not already present
  2231. if ( !empty($import_id) ) {
  2232. $import_id = (int) $import_id;
  2233. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  2234. $data['ID'] = $import_id;
  2235. }
  2236. }
  2237. if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
  2238. if ( $wp_error )
  2239. return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
  2240. else
  2241. return 0;
  2242. }
  2243. $post_ID = (int) $wpdb->insert_id;
  2244. // use the newly generated $post_ID
  2245. $where = array( 'ID' => $post_ID );
  2246. }
  2247. if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
  2248. $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
  2249. $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  2250. }
  2251. if ( is_object_in_taxonomy($post_type, 'category') )
  2252. wp_set_post_categories( $post_ID, $post_category );
  2253. if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
  2254. wp_set_post_tags( $post_ID, $tags_input );
  2255. // new-style support for all custom taxonomies
  2256. if ( !empty($tax_input) ) {
  2257. foreach ( $tax_input as $taxonomy => $tags ) {
  2258. $taxonomy_obj = get_taxonomy($taxonomy);
  2259. if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
  2260. $tags = array_filter($tags);
  2261. if ( current_user_can($taxonomy_obj->cap->assign_terms) )
  2262. wp_set_post_terms( $post_ID, $tags, $taxonomy );
  2263. }
  2264. }
  2265. $current_guid = get_post_field( 'guid', $post_ID );
  2266. if ( 'page' == $data['post_type'] )
  2267. clean_page_cache($post_ID);
  2268. else
  2269. clean_post_cache($post_ID);
  2270. // Set GUID
  2271. if ( !$update && '' == $current_guid )
  2272. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  2273. $post = get_post($post_ID);
  2274. if ( !empty($page_template) && 'page' == $data['post_type'] ) {
  2275. $post->page_template = $page_template;
  2276. $page_templates = get_page_templates();
  2277. if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
  2278. if ( $wp_error )
  2279. return new WP_Error('invalid_page_template', __('The page template is invalid.'));
  2280. else
  2281. return 0;
  2282. }
  2283. update_post_meta($post_ID, '_wp_page_template', $page_template);
  2284. }
  2285. wp_transition_post_status($data['post_status'], $previous_status, $post);
  2286. if ( $update ) {
  2287. do_action('edit_post', $post_ID, $post);
  2288. $post_after = get_post($post_ID);
  2289. do_action( 'post_updated', $post_ID, $post_after, $post_before);
  2290. }
  2291. do_action('save_post', $post_ID, $post);
  2292. do_action('wp_insert_post', $post_ID, $post);
  2293. return $post_ID;
  2294. }
  2295. /**
  2296. * Update a post with new post data.
  2297. *
  2298. * The date does not have to be set for drafts. You can set the date and it will
  2299. * not be overridden.
  2300. *
  2301. * @since 1.0.0
  2302. *
  2303. * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
  2304. * @return int 0 on failure, Post ID on success.
  2305. */
  2306. function wp_update_post($postarr = array()) {
  2307. if ( is_object($postarr) ) {
  2308. // non-escaped post was passed
  2309. $postarr = get_object_vars($postarr);
  2310. $postarr = add_magic_quotes($postarr);
  2311. }
  2312. // First, get all of the original fields
  2313. $post = wp_get_single_post($postarr['ID'], ARRAY_A);
  2314. // Escape data pulled from DB.
  2315. $post = add_magic_quotes($post);
  2316. // Passed post category list overwrites existing category list if not empty.
  2317. if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
  2318. && 0 != count($postarr['post_category']) )
  2319. $post_cats = $postarr['post_category'];
  2320. else
  2321. $post_cats = $post['post_category'];
  2322. // Drafts shouldn't be assigned a date unless explicitly done so by the user
  2323. if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
  2324. ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  2325. $clear_date = true;
  2326. else
  2327. $clear_date = false;
  2328. // Merge old and new fields with new fields overwriting old ones.
  2329. $postarr = array_merge($post, $postarr);
  2330. $postarr['post_category'] = $post_cats;
  2331. if ( $clear_date ) {
  2332. $postarr['post_date'] = current_time('mysql');
  2333. $postarr['post_date_gmt'] = '';
  2334. }
  2335. if ($postarr['post_type'] == 'attachment')
  2336. return wp_insert_attachment($postarr);
  2337. return wp_insert_post($postarr);
  2338. }
  2339. /**
  2340. * Publish a post by transitioning the post status.
  2341. *
  2342. * @since 2.1.0
  2343. * @uses $wpdb
  2344. * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
  2345. *
  2346. * @param int $post_id Post ID.
  2347. * @return null
  2348. */
  2349. function wp_publish_post($post_id) {
  2350. global $wpdb;
  2351. $post = get_post($post_id);
  2352. if ( empty($post) )
  2353. return;
  2354. if ( 'publish' == $post->post_status )
  2355. return;
  2356. $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
  2357. $old_status = $post->post_status;
  2358. $post->post_status = 'publish';
  2359. wp_transition_post_status('publish', $old_status, $post);
  2360. // Update counts for the post's terms.
  2361. foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
  2362. $tt_ids = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'tt_ids'));
  2363. wp_update_term_count($tt_ids, $taxonomy);
  2364. }
  2365. do_action('edit_post', $post_id, $post);
  2366. do_action('save_post', $post_id, $post);
  2367. do_action('wp_insert_post', $post_id, $post);
  2368. }
  2369. /**
  2370. * Publish future post and make sure post ID has future post status.
  2371. *
  2372. * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
  2373. * from publishing drafts, etc.
  2374. *
  2375. * @since 2.5.0
  2376. *
  2377. * @param int $post_id Post ID.
  2378. * @return null Nothing is returned. Which can mean that no action is required or post was published.
  2379. */
  2380. function check_and_publish_future_post($post_id) {
  2381. $post = get_post($post_id);
  2382. if ( empty($post) )
  2383. return;
  2384. if ( 'future' != $post->post_status )
  2385. return;
  2386. $time = strtotime( $post->post_date_gmt . ' GMT' );
  2387. if ( $time > time() ) { // Uh oh, someone jumped the gun!
  2388. wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
  2389. wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  2390. return;
  2391. }
  2392. return wp_publish_post($post_id);
  2393. }
  2394. /**
  2395. * Computes a unique slug for the post, when given the desired slug and some post details.
  2396. *
  2397. * @since 2.8.0
  2398. *
  2399. * @global wpdb $wpdb
  2400. * @global WP_Rewrite $wp_rewrite
  2401. * @param string $slug the desired slug (post_name)
  2402. * @param integer $post_ID
  2403. * @param string $post_status no uniqueness checks are made if the post is still draft or pending
  2404. * @param string $post_type
  2405. * @param integer $post_parent
  2406. * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  2407. */
  2408. function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
  2409. if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  2410. return $slug;
  2411. global $wpdb, $wp_rewrite;
  2412. $feeds = $wp_rewrite->feeds;
  2413. if ( ! is_array( $feeds ) )
  2414. $feeds = array();
  2415. $hierarchical_post_types = get_post_types( array('hierarchical' => true) );
  2416. if ( 'attachment' == $post_type ) {
  2417. // Attachment slugs must be unique across all types.
  2418. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  2419. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
  2420. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
  2421. $suffix = 2;
  2422. do {
  2423. $alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2424. $post_name_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_post_name, $post_ID ) );
  2425. $suffix++;
  2426. } while ( $post_name_check );
  2427. $slug = $alt_post_name;
  2428. }
  2429. } elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
  2430. // Page slugs must be unique within their own trees. Pages are in a separate
  2431. // namespace than posts so page slugs are allowed to overlap post slugs.
  2432. $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";
  2433. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
  2434. 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 ) ) {
  2435. $suffix = 2;
  2436. do {
  2437. $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2438. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
  2439. $suffix++;
  2440. } while ( $post_name_check );
  2441. $slug = $alt_post_name;
  2442. }
  2443. } else {
  2444. // Post slugs must be unique across all posts.
  2445. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  2446. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
  2447. if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
  2448. $suffix = 2;
  2449. do {
  2450. $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2451. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
  2452. $suffix++;
  2453. } while ( $post_name_check );
  2454. $slug = $alt_post_name;
  2455. }
  2456. }
  2457. return $slug;
  2458. }
  2459. /**
  2460. * Adds tags to a post.
  2461. *
  2462. * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
  2463. *
  2464. * @package WordPress
  2465. * @subpackage Post
  2466. * @since 2.3.0
  2467. *
  2468. * @param int $post_id Post ID
  2469. * @param string $tags The tags to set for the post, separated by commas.
  2470. * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
  2471. */
  2472. function wp_add_post_tags($post_id = 0, $tags = '') {
  2473. return wp_set_post_tags($post_id, $tags, true);
  2474. }
  2475. /**
  2476. * Set the tags for a post.
  2477. *
  2478. * @since 2.3.0
  2479. * @uses wp_set_object_terms() Sets the tags for the post.
  2480. *
  2481. * @param int $post_id Post ID.
  2482. * @param string $tags The tags to set for the post, separated by commas.
  2483. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2484. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2485. */
  2486. function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  2487. return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
  2488. }
  2489. /**
  2490. * Set the terms for a post.
  2491. *
  2492. * @since 2.8.0
  2493. * @uses wp_set_object_terms() Sets the tags for the post.
  2494. *
  2495. * @param int $post_id Post ID.
  2496. * @param string $tags The tags to set for the post, separated by commas.
  2497. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2498. * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2499. */
  2500. function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  2501. $post_id = (int) $post_id;
  2502. if ( !$post_id )
  2503. return false;
  2504. if ( empty($tags) )
  2505. $tags = array();
  2506. $tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
  2507. // Hierarchical taxonomies must always pass IDs rather than names so that children with the same
  2508. // names but different parents aren't confused.
  2509. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  2510. $tags = array_map( 'intval', $tags );
  2511. $tags = array_unique( $tags );
  2512. }
  2513. return wp_set_object_terms($post_id, $tags, $taxonomy, $append);
  2514. }
  2515. /**
  2516. * Set categories for a post.
  2517. *
  2518. * If the post categories parameter is not set, then the default category is
  2519. * going used.
  2520. *
  2521. * @since 2.1.0
  2522. *
  2523. * @param int $post_ID Post ID.
  2524. * @param array $post_categories Optional. List of categories.
  2525. * @return bool|mixed
  2526. */
  2527. function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
  2528. $post_ID = (int) $post_ID;
  2529. $post_type = get_post_type( $post_ID );
  2530. $post_status = get_post_status( $post_ID );
  2531. // If $post_categories isn't already an array, make it one:
  2532. if ( !is_array($post_categories) || empty($post_categories) ) {
  2533. if ( 'post' == $post_type && 'auto-draft' != $post_status )
  2534. $post_categories = array( get_option('default_category') );
  2535. else
  2536. $post_categories = array();
  2537. } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
  2538. return true;
  2539. }
  2540. if ( !empty($post_categories) ) {
  2541. $post_categories = array_map('intval', $post_categories);
  2542. $post_categories = array_unique($post_categories);
  2543. }
  2544. return wp_set_object_terms($post_ID, $post_categories, 'category');
  2545. }
  2546. /**
  2547. * Transition the post status of a post.
  2548. *
  2549. * Calls hooks to transition post status.
  2550. *
  2551. * The first is 'transition_post_status' with new status, old status, and post data.
  2552. *
  2553. * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
  2554. * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
  2555. * post data.
  2556. *
  2557. * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
  2558. * parameter and POSTTYPE is post_type post data.
  2559. *
  2560. * @since 2.3.0
  2561. * @link http://codex.wordpress.org/Post_Status_Transitions
  2562. *
  2563. * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
  2564. * $post if there is a status change.
  2565. * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
  2566. * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
  2567. *
  2568. * @param string $new_status Transition to this post status.
  2569. * @param string $old_status Previous post status.
  2570. * @param object $post Post data.
  2571. */
  2572. function wp_transition_post_status($new_status, $old_status, $post) {
  2573. do_action('transition_post_status', $new_status, $old_status, $post);
  2574. do_action("{$old_status}_to_{$new_status}", $post);
  2575. do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
  2576. }
  2577. //
  2578. // Trackback and ping functions
  2579. //
  2580. /**
  2581. * Add a URL to those already pung.
  2582. *
  2583. * @since 1.5.0
  2584. * @uses $wpdb
  2585. *
  2586. * @param int $post_id Post ID.
  2587. * @param string $uri Ping URI.
  2588. * @return int How many rows were updated.
  2589. */
  2590. function add_ping($post_id, $uri) {
  2591. global $wpdb;
  2592. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2593. $pung = trim($pung);
  2594. $pung = preg_split('/\s/', $pung);
  2595. $pung[] = $uri;
  2596. $new = implode("\n", $pung);
  2597. $new = apply_filters('add_ping', $new);
  2598. // expected_slashed ($new)
  2599. $new = stripslashes($new);
  2600. return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
  2601. }
  2602. /**
  2603. * Retrieve enclosures already enclosed for a post.
  2604. *
  2605. * @since 1.5.0
  2606. * @uses $wpdb
  2607. *
  2608. * @param int $post_id Post ID.
  2609. * @return array List of enclosures
  2610. */
  2611. function get_enclosed($post_id) {
  2612. $custom_fields = get_post_custom( $post_id );
  2613. $pung = array();
  2614. if ( !is_array( $custom_fields ) )
  2615. return $pung;
  2616. foreach ( $custom_fields as $key => $val ) {
  2617. if ( 'enclosure' != $key || !is_array( $val ) )
  2618. continue;
  2619. foreach( $val as $enc ) {
  2620. $enclosure = split( "\n", $enc );
  2621. $pung[] = trim( $enclosure[ 0 ] );
  2622. }
  2623. }
  2624. $pung = apply_filters('get_enclosed', $pung, $post_id);
  2625. return $pung;
  2626. }
  2627. /**
  2628. * Retrieve URLs already pinged for a post.
  2629. *
  2630. * @since 1.5.0
  2631. * @uses $wpdb
  2632. *
  2633. * @param int $post_id Post ID.
  2634. * @return array
  2635. */
  2636. function get_pung($post_id) {
  2637. global $wpdb;
  2638. $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2639. $pung = trim($pung);
  2640. $pung = preg_split('/\s/', $pung);
  2641. $pung = apply_filters('get_pung', $pung);
  2642. return $pung;
  2643. }
  2644. /**
  2645. * Retrieve URLs that need to be pinged.
  2646. *
  2647. * @since 1.5.0
  2648. * @uses $wpdb
  2649. *
  2650. * @param int $post_id Post ID
  2651. * @return array
  2652. */
  2653. function get_to_ping($post_id) {
  2654. global $wpdb;
  2655. $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2656. $to_ping = trim($to_ping);
  2657. $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
  2658. $to_ping = apply_filters('get_to_ping', $to_ping);
  2659. return $to_ping;
  2660. }
  2661. /**
  2662. * Do trackbacks for a list of URLs.
  2663. *
  2664. * @since 1.0.0
  2665. *
  2666. * @param string $tb_list Comma separated list of URLs
  2667. * @param int $post_id Post ID
  2668. */
  2669. function trackback_url_list($tb_list, $post_id) {
  2670. if ( ! empty( $tb_list ) ) {
  2671. // get post data
  2672. $postdata = wp_get_single_post($post_id, ARRAY_A);
  2673. // import postdata as variables
  2674. extract($postdata, EXTR_SKIP);
  2675. // form an excerpt
  2676. $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
  2677. if (strlen($excerpt) > 255) {
  2678. $excerpt = substr($excerpt,0,252) . '...';
  2679. }
  2680. $trackback_urls = explode(',', $tb_list);
  2681. foreach( (array) $trackback_urls as $tb_url) {
  2682. $tb_url = trim($tb_url);
  2683. trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
  2684. }
  2685. }
  2686. }
  2687. //
  2688. // Page functions
  2689. //
  2690. /**
  2691. * Get a list of page IDs.
  2692. *
  2693. * @since 2.0.0
  2694. * @uses $wpdb
  2695. *
  2696. * @return array List of page IDs.
  2697. */
  2698. function get_all_page_ids() {
  2699. global $wpdb;
  2700. if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
  2701. $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
  2702. wp_cache_add('all_page_ids', $page_ids, 'posts');
  2703. }
  2704. return $page_ids;
  2705. }
  2706. /**
  2707. * Retrieves page data given a page ID or page object.
  2708. *
  2709. * @since 1.5.1
  2710. *
  2711. * @param mixed $page Page object or page ID. Passed by reference.
  2712. * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
  2713. * @param string $filter How the return value should be filtered.
  2714. * @return mixed Page data.
  2715. */
  2716. function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
  2717. $p = get_post($page, $output, $filter);
  2718. return $p;
  2719. }
  2720. /**
  2721. * Retrieves a page given its path.
  2722. *
  2723. * @since 2.1.0
  2724. * @uses $wpdb
  2725. *
  2726. * @param string $page_path Page path
  2727. * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
  2728. * @param string $post_type Optional. Post type. Default page.
  2729. * @return mixed Null when complete.
  2730. */
  2731. function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
  2732. global $wpdb;
  2733. $null = null;
  2734. $page_path = rawurlencode(urldecode($page_path));
  2735. $page_path = str_replace('%2F', '/', $page_path);
  2736. $page_path = str_replace('%20', ' ', $page_path);
  2737. $page_paths = '/' . trim($page_path, '/');
  2738. $leaf_path = sanitize_title(basename($page_paths));
  2739. $page_paths = explode('/', $page_paths);
  2740. $full_path = '';
  2741. foreach ( (array) $page_paths as $pathdir )
  2742. $full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title($pathdir);
  2743. $pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = %s OR post_type = 'attachment')", $leaf_path, $post_type ));
  2744. if ( empty($pages) )
  2745. return $null;
  2746. foreach ( $pages as $page ) {
  2747. $path = '/' . $leaf_path;
  2748. $curpage = $page;
  2749. while ( $curpage->post_parent != 0 ) {
  2750. $post_parent = $curpage->post_parent;
  2751. $curpage = wp_cache_get( $post_parent, 'posts' );
  2752. if ( false === $curpage )
  2753. $curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type = %s", $post_parent, $post_type ) );
  2754. $path = '/' . $curpage->post_name . $path;
  2755. }
  2756. if ( $path == $full_path )
  2757. return get_page($page->ID, $output, $post_type);
  2758. }
  2759. return $null;
  2760. }
  2761. /**
  2762. * Retrieve a page given its title.
  2763. *
  2764. * @since 2.1.0
  2765. * @uses $wpdb
  2766. *
  2767. * @param string $page_title Page title
  2768. * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
  2769. * @param string $post_type Optional. Post type. Default page.
  2770. * @return mixed
  2771. */
  2772. function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
  2773. global $wpdb;
  2774. $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
  2775. if ( $page )
  2776. return get_page($page, $output);
  2777. return null;
  2778. }
  2779. /**
  2780. * Retrieve child pages from list of pages matching page ID.
  2781. *
  2782. * Matches against the pages parameter against the page ID. Also matches all
  2783. * children for the same to retrieve all children of a page. Does not make any
  2784. * SQL queries to get the children.
  2785. *
  2786. * @since 1.5.1
  2787. *
  2788. * @param int $page_id Page ID.
  2789. * @param array $pages List of pages' objects.
  2790. * @return array
  2791. */
  2792. function &get_page_children($page_id, $pages) {
  2793. $page_list = array();
  2794. foreach ( (array) $pages as $page ) {
  2795. if ( $page->post_parent == $page_id ) {
  2796. $page_list[] = $page;
  2797. if ( $children = get_page_children($page->ID, $pages) )
  2798. $page_list = array_merge($page_list, $children);
  2799. }
  2800. }
  2801. return $page_list;
  2802. }
  2803. /**
  2804. * Order the pages with children under parents in a flat list.
  2805. *
  2806. * It uses auxiliary structure to hold parent-children relationships and
  2807. * runs in O(N) complexity
  2808. *
  2809. * @since 2.0.0
  2810. *
  2811. * @param array $pages Posts array.
  2812. * @param int $page_id Parent page ID.
  2813. * @return array A list arranged by hierarchy. Children immediately follow their parents.
  2814. */
  2815. function &get_page_hierarchy( &$pages, $page_id = 0 ) {
  2816. if ( empty( $pages ) ) {
  2817. $result = array();
  2818. return $result;
  2819. }
  2820. $children = array();
  2821. foreach ( (array) $pages as $p ) {
  2822. $parent_id = intval( $p->post_parent );
  2823. $children[ $parent_id ][] = $p;
  2824. }
  2825. $result = array();
  2826. _page_traverse_name( $page_id, $children, $result );
  2827. return $result;
  2828. }
  2829. /**
  2830. * function to traverse and return all the nested children post names of a root page.
  2831. * $children contains parent-chilren relations
  2832. *
  2833. * @since 2.9.0
  2834. */
  2835. function _page_traverse_name( $page_id, &$children, &$result ){
  2836. if ( isset( $children[ $page_id ] ) ){
  2837. foreach( (array)$children[ $page_id ] as $child ) {
  2838. $result[ $child->ID ] = $child->post_name;
  2839. _page_traverse_name( $child->ID, $children, $result );
  2840. }
  2841. }
  2842. }
  2843. /**
  2844. * Builds URI for a page.
  2845. *
  2846. * Sub pages will be in the "directory" under the parent page post name.
  2847. *
  2848. * @since 1.5.0
  2849. *
  2850. * @param mixed $page Page object or page ID.
  2851. * @return string Page URI.
  2852. */
  2853. function get_page_uri($page) {
  2854. if ( ! is_object($page) )
  2855. $page = get_page($page);
  2856. $uri = $page->post_name;
  2857. // A page cannot be it's own parent.
  2858. if ( $page->post_parent == $page->ID )
  2859. return $uri;
  2860. while ($page->post_parent != 0) {
  2861. $page = get_page($page->post_parent);
  2862. $uri = $page->post_name . "/" . $uri;
  2863. }
  2864. return $uri;
  2865. }
  2866. /**
  2867. * Retrieve a list of pages.
  2868. *
  2869. * The defaults that can be overridden are the following: 'child_of',
  2870. * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
  2871. * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
  2872. *
  2873. * @since 1.5.0
  2874. * @uses $wpdb
  2875. *
  2876. * @param mixed $args Optional. Array or string of options that overrides defaults.
  2877. * @return array List of pages matching defaults or $args
  2878. */
  2879. function &get_pages($args = '') {
  2880. global $wpdb;
  2881. $defaults = array(
  2882. 'child_of' => 0, 'sort_order' => 'ASC',
  2883. 'sort_column' => 'post_title', 'hierarchical' => 1,
  2884. 'exclude' => array(), 'include' => array(),
  2885. 'meta_key' => '', 'meta_value' => '',
  2886. 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
  2887. 'number' => '', 'offset' => 0,
  2888. 'post_type' => 'page', 'post_status' => 'publish',
  2889. );
  2890. $r = wp_parse_args( $args, $defaults );
  2891. extract( $r, EXTR_SKIP );
  2892. $number = (int) $number;
  2893. $offset = (int) $offset;
  2894. // Make sure the post type is hierarchical
  2895. $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
  2896. if ( !in_array( $post_type, $hierarchical_post_types ) )
  2897. return false;
  2898. // Make sure we have a valid post status
  2899. if ( !is_array( $post_status ) )
  2900. $post_status = explode( ',', $post_status );
  2901. if ( array_diff( $post_status, get_post_stati() ) )
  2902. return false;
  2903. $cache = array();
  2904. $key = md5( serialize( compact(array_keys($defaults)) ) );
  2905. if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
  2906. if ( is_array($cache) && isset( $cache[ $key ] ) ) {
  2907. $pages = apply_filters('get_pages', $cache[ $key ], $r );
  2908. return $pages;
  2909. }
  2910. }
  2911. if ( !is_array($cache) )
  2912. $cache = array();
  2913. $inclusions = '';
  2914. if ( !empty($include) ) {
  2915. $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
  2916. $parent = -1;
  2917. $exclude = '';
  2918. $meta_key = '';
  2919. $meta_value = '';
  2920. $hierarchical = false;
  2921. $incpages = wp_parse_id_list( $include );
  2922. if ( ! empty( $incpages ) ) {
  2923. foreach ( $incpages as $incpage ) {
  2924. if (empty($inclusions))
  2925. $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
  2926. else
  2927. $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
  2928. }
  2929. }
  2930. }
  2931. if (!empty($inclusions))
  2932. $inclusions .= ')';
  2933. $exclusions = '';
  2934. if ( !empty($exclude) ) {
  2935. $expages = wp_parse_id_list( $exclude );
  2936. if ( ! empty( $expages ) ) {
  2937. foreach ( $expages as $expage ) {
  2938. if (empty($exclusions))
  2939. $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
  2940. else
  2941. $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
  2942. }
  2943. }
  2944. }
  2945. if (!empty($exclusions))
  2946. $exclusions .= ')';
  2947. $author_query = '';
  2948. if (!empty($authors)) {
  2949. $post_authors = preg_split('/[\s,]+/',$authors);
  2950. if ( ! empty( $post_authors ) ) {
  2951. foreach ( $post_authors as $post_author ) {
  2952. //Do we have an author id or an author login?
  2953. if ( 0 == intval($post_author) ) {
  2954. $post_author = get_userdatabylogin($post_author);
  2955. if ( empty($post_author) )
  2956. continue;
  2957. if ( empty($post_author->ID) )
  2958. continue;
  2959. $post_author = $post_author->ID;
  2960. }
  2961. if ( '' == $author_query )
  2962. $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
  2963. else
  2964. $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
  2965. }
  2966. if ( '' != $author_query )
  2967. $author_query = " AND ($author_query)";
  2968. }
  2969. }
  2970. $join = '';
  2971. $where = "$exclusions $inclusions ";
  2972. if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
  2973. $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
  2974. // meta_key and meta_value might be slashed
  2975. $meta_key = stripslashes($meta_key);
  2976. $meta_value = stripslashes($meta_value);
  2977. if ( ! empty( $meta_key ) )
  2978. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
  2979. if ( ! empty( $meta_value ) )
  2980. $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
  2981. }
  2982. if ( $parent >= 0 )
  2983. $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
  2984. if ( 1 == count( $post_status ) ) {
  2985. $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
  2986. } else {
  2987. $post_status = implode( "', '", $post_status );
  2988. $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
  2989. }
  2990. $orderby_array = array();
  2991. $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'modified',
  2992. 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
  2993. 'ID', 'rand', 'comment_count');
  2994. foreach ( explode( ',', $sort_column ) as $orderby ) {
  2995. $orderby = trim( $orderby );
  2996. if ( !in_array( $orderby, $allowed_keys ) )
  2997. continue;
  2998. switch ( $orderby ) {
  2999. case 'menu_order':
  3000. break;
  3001. case 'ID':
  3002. $orderby = "$wpdb->posts.ID";
  3003. break;
  3004. case 'rand':
  3005. $orderby = 'RAND()';
  3006. break;
  3007. case 'comment_count':
  3008. $orderby = "$wpdb->posts.comment_count";
  3009. break;
  3010. default:
  3011. if ( 0 === strpos( $orderby, 'post_' ) )
  3012. $orderby = "$wpdb->posts." . $orderby;
  3013. else
  3014. $orderby = "$wpdb->posts.post_" . $orderby;
  3015. }
  3016. $orderby_array[] = $orderby;
  3017. }
  3018. $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
  3019. $sort_order = strtoupper( $sort_order );
  3020. if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
  3021. $sort_order = 'ASC';
  3022. $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
  3023. $query .= $author_query;
  3024. $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
  3025. if ( !empty($number) )
  3026. $query .= ' LIMIT ' . $offset . ',' . $number;
  3027. $pages = $wpdb->get_results($query);
  3028. if ( empty($pages) ) {
  3029. $pages = apply_filters('get_pages', array(), $r);
  3030. return $pages;
  3031. }
  3032. // Sanitize before caching so it'll only get done once
  3033. $num_pages = count($pages);
  3034. for ($i = 0; $i < $num_pages; $i++) {
  3035. $pages[$i] = sanitize_post($pages[$i], 'raw');
  3036. }
  3037. // Update cache.
  3038. update_page_cache($pages);
  3039. if ( $child_of || $hierarchical )
  3040. $pages = & get_page_children($child_of, $pages);
  3041. if ( !empty($exclude_tree) ) {
  3042. $exclude = (int) $exclude_tree;
  3043. $children = get_page_children($exclude, $pages);
  3044. $excludes = array();
  3045. foreach ( $children as $child )
  3046. $excludes[] = $child->ID;
  3047. $excludes[] = $exclude;
  3048. $num_pages = count($pages);
  3049. for ( $i = 0; $i < $num_pages; $i++ ) {
  3050. if ( in_array($pages[$i]->ID, $excludes) )
  3051. unset($pages[$i]);
  3052. }
  3053. }
  3054. $cache[ $key ] = $pages;
  3055. wp_cache_set( 'get_pages', $cache, 'posts' );
  3056. $pages = apply_filters('get_pages', $pages, $r);
  3057. return $pages;
  3058. }
  3059. //
  3060. // Attachment functions
  3061. //
  3062. /**
  3063. * Check if the attachment URI is local one and is really an attachment.
  3064. *
  3065. * @since 2.0.0
  3066. *
  3067. * @param string $url URL to check
  3068. * @return bool True on success, false on failure.
  3069. */
  3070. function is_local_attachment($url) {
  3071. if (strpos($url, home_url()) === false)
  3072. return false;
  3073. if (strpos($url, home_url('/?attachment_id=')) !== false)
  3074. return true;
  3075. if ( $id = url_to_postid($url) ) {
  3076. $post = & get_post($id);
  3077. if ( 'attachment' == $post->post_type )
  3078. return true;
  3079. }
  3080. return false;
  3081. }
  3082. /**
  3083. * Insert an attachment.
  3084. *
  3085. * If you set the 'ID' in the $object parameter, it will mean that you are
  3086. * updating and attempt to update the attachment. You can also set the
  3087. * attachment name or title by setting the key 'post_name' or 'post_title'.
  3088. *
  3089. * You can set the dates for the attachment manually by setting the 'post_date'
  3090. * and 'post_date_gmt' keys' values.
  3091. *
  3092. * By default, the comments will use the default settings for whether the
  3093. * comments are allowed. You can close them manually or keep them open by
  3094. * setting the value for the 'comment_status' key.
  3095. *
  3096. * The $object parameter can have the following:
  3097. * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
  3098. * 'post_type' - Default is 'post', will be set to attachment. Can not override.
  3099. * 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
  3100. * 'ping_status' - Default is the value in default ping status option. Whether the attachment
  3101. * can accept pings.
  3102. * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
  3103. * to, if any.
  3104. * 'menu_order' - Default is 0. The order it is displayed.
  3105. * 'to_ping' - Whether to ping.
  3106. * 'pinged' - Default is empty string.
  3107. * 'post_password' - Default is empty string. The password to access the attachment.
  3108. * 'guid' - Global Unique ID for referencing the attachment.
  3109. * 'post_content_filtered' - Attachment post content filtered.
  3110. * 'post_excerpt' - Attachment excerpt.
  3111. *
  3112. * @since 2.0.0
  3113. * @uses $wpdb
  3114. * @uses $user_ID
  3115. * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
  3116. * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
  3117. *
  3118. * @param string|array $object Arguments to override defaults.
  3119. * @param string $file Optional filename.
  3120. * @param int $parent Parent post ID.
  3121. * @return int Attachment ID.
  3122. */
  3123. function wp_insert_attachment($object, $file = false, $parent = 0) {
  3124. global $wpdb, $user_ID;
  3125. $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_ID,
  3126. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  3127. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  3128. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
  3129. $object = wp_parse_args($object, $defaults);
  3130. if ( !empty($parent) )
  3131. $object['post_parent'] = $parent;
  3132. unset( $object[ 'filter' ] );
  3133. $object = sanitize_post($object, 'db');
  3134. // export array as variables
  3135. extract($object, EXTR_SKIP);
  3136. if ( empty($post_author) )
  3137. $post_author = $user_ID;
  3138. $post_type = 'attachment';
  3139. if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
  3140. $post_status = 'inherit';
  3141. // Make sure we set a valid category.
  3142. if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  3143. // 'post' requires at least one category.
  3144. if ( 'post' == $post_type )
  3145. $post_category = array( get_option('default_category') );
  3146. else
  3147. $post_category = array();
  3148. }
  3149. // Are we updating or creating?
  3150. if ( !empty($ID) ) {
  3151. $update = true;
  3152. $post_ID = (int) $ID;
  3153. } else {
  3154. $update = false;
  3155. $post_ID = 0;
  3156. }
  3157. // Create a valid post name.
  3158. if ( empty($post_name) )
  3159. $post_name = sanitize_title($post_title);
  3160. else
  3161. $post_name = sanitize_title($post_name);
  3162. // expected_slashed ($post_name)
  3163. $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
  3164. if ( empty($post_date) )
  3165. $post_date = current_time('mysql');
  3166. if ( empty($post_date_gmt) )
  3167. $post_date_gmt = current_time('mysql', 1);
  3168. if ( empty($post_modified) )
  3169. $post_modified = $post_date;
  3170. if ( empty($post_modified_gmt) )
  3171. $post_modified_gmt = $post_date_gmt;
  3172. if ( empty($comment_status) ) {
  3173. if ( $update )
  3174. $comment_status = 'closed';
  3175. else
  3176. $comment_status = get_option('default_comment_status');
  3177. }
  3178. if ( empty($ping_status) )
  3179. $ping_status = get_option('default_ping_status');
  3180. if ( isset($to_ping) )
  3181. $to_ping = preg_replace('|\s+|', "\n", $to_ping);
  3182. else
  3183. $to_ping = '';
  3184. if ( isset($post_parent) )
  3185. $post_parent = (int) $post_parent;
  3186. else
  3187. $post_parent = 0;
  3188. if ( isset($menu_order) )
  3189. $menu_order = (int) $menu_order;
  3190. else
  3191. $menu_order = 0;
  3192. if ( !isset($post_password) )
  3193. $post_password = '';
  3194. if ( ! isset($pinged) )
  3195. $pinged = '';
  3196. // expected_slashed (everything!)
  3197. $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' ) );
  3198. $data = stripslashes_deep( $data );
  3199. if ( $update ) {
  3200. $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
  3201. } else {
  3202. // If there is a suggested ID, use it if not already present
  3203. if ( !empty($import_id) ) {
  3204. $import_id = (int) $import_id;
  3205. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  3206. $data['ID'] = $import_id;
  3207. }
  3208. }
  3209. $wpdb->insert( $wpdb->posts, $data );
  3210. $post_ID = (int) $wpdb->insert_id;
  3211. }
  3212. if ( empty($post_name) ) {
  3213. $post_name = sanitize_title($post_title, $post_ID);
  3214. $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
  3215. }
  3216. wp_set_post_categories($post_ID, $post_category);
  3217. if ( $file )
  3218. update_attached_file( $post_ID, $file );
  3219. clean_post_cache($post_ID);
  3220. if ( isset($post_parent) && $post_parent < 0 )
  3221. add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
  3222. if ( ! empty( $context ) )
  3223. add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
  3224. if ( $update) {
  3225. do_action('edit_attachment', $post_ID);
  3226. } else {
  3227. do_action('add_attachment', $post_ID);
  3228. }
  3229. return $post_ID;
  3230. }
  3231. /**
  3232. * Trashes or deletes an attachment.
  3233. *
  3234. * When an attachment is permanently deleted, the file will also be removed.
  3235. * Deletion removes all post meta fields, taxonomy, comments, etc. associated
  3236. * with the attachment (except the main post).
  3237. *
  3238. * The attachment is moved to the trash instead of permanently deleted unless trash
  3239. * for media is disabled, item is already in the trash, or $force_delete is true.
  3240. *
  3241. * @since 2.0.0
  3242. * @uses $wpdb
  3243. * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
  3244. *
  3245. * @param int $post_id Attachment ID.
  3246. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  3247. * @return mixed False on failure. Post data on success.
  3248. */
  3249. function wp_delete_attachment( $post_id, $force_delete = false ) {
  3250. global $wpdb;
  3251. if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
  3252. return $post;
  3253. if ( 'attachment' != $post->post_type )
  3254. return false;
  3255. if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
  3256. return wp_trash_post( $post_id );
  3257. delete_post_meta($post_id, '_wp_trash_meta_status');
  3258. delete_post_meta($post_id, '_wp_trash_meta_time');
  3259. $meta = wp_get_attachment_metadata( $post_id );
  3260. $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  3261. $file = get_attached_file( $post_id );
  3262. if ( is_multisite() )
  3263. delete_transient( 'dirsize_cache' );
  3264. do_action('delete_attachment', $post_id);
  3265. wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
  3266. wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
  3267. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND meta_value = %d", $post_id ));
  3268. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
  3269. if ( ! empty( $comment_ids ) ) {
  3270. do_action( 'delete_comment', $comment_ids );
  3271. foreach ( $comment_ids as $comment_id )
  3272. wp_delete_comment( $comment_id, true );
  3273. do_action( 'deleted_comment', $comment_ids );
  3274. }
  3275. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
  3276. if ( !empty($post_meta_ids) ) {
  3277. do_action( 'delete_postmeta', $post_meta_ids );
  3278. $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
  3279. $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
  3280. do_action( 'deleted_postmeta', $post_meta_ids );
  3281. }
  3282. do_action( 'delete_post', $post_id );
  3283. $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3284. do_action( 'deleted_post', $post_id );
  3285. $uploadpath = wp_upload_dir();
  3286. if ( ! empty($meta['thumb']) ) {
  3287. // Don't delete the thumb if another attachment uses it
  3288. 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)) ) {
  3289. $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
  3290. $thumbfile = apply_filters('wp_delete_file', $thumbfile);
  3291. @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
  3292. }
  3293. }
  3294. // remove intermediate and backup images if there are any
  3295. foreach ( get_intermediate_image_sizes() as $size ) {
  3296. if ( $intermediate = image_get_intermediate_size($post_id, $size) ) {
  3297. $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
  3298. @ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
  3299. }
  3300. }
  3301. if ( is_array($backup_sizes) ) {
  3302. foreach ( $backup_sizes as $size ) {
  3303. $del_file = path_join( dirname($meta['file']), $size['file'] );
  3304. $del_file = apply_filters('wp_delete_file', $del_file);
  3305. @ unlink( path_join($uploadpath['basedir'], $del_file) );
  3306. }
  3307. }
  3308. $file = apply_filters('wp_delete_file', $file);
  3309. if ( ! empty($file) )
  3310. @ unlink($file);
  3311. clean_post_cache($post_id);
  3312. return $post;
  3313. }
  3314. /**
  3315. * Retrieve attachment meta field for attachment ID.
  3316. *
  3317. * @since 2.1.0
  3318. *
  3319. * @param int $post_id Attachment ID
  3320. * @param bool $unfiltered Optional, default is false. If true, filters are not run.
  3321. * @return string|bool Attachment meta field. False on failure.
  3322. */
  3323. function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
  3324. $post_id = (int) $post_id;
  3325. if ( !$post =& get_post( $post_id ) )
  3326. return false;
  3327. $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
  3328. if ( $unfiltered )
  3329. return $data;
  3330. return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
  3331. }
  3332. /**
  3333. * Update metadata for an attachment.
  3334. *
  3335. * @since 2.1.0
  3336. *
  3337. * @param int $post_id Attachment ID.
  3338. * @param array $data Attachment data.
  3339. * @return int
  3340. */
  3341. function wp_update_attachment_metadata( $post_id, $data ) {
  3342. $post_id = (int) $post_id;
  3343. if ( !$post =& get_post( $post_id ) )
  3344. return false;
  3345. $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
  3346. return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
  3347. }
  3348. /**
  3349. * Retrieve the URL for an attachment.
  3350. *
  3351. * @since 2.1.0
  3352. *
  3353. * @param int $post_id Attachment ID.
  3354. * @return string
  3355. */
  3356. function wp_get_attachment_url( $post_id = 0 ) {
  3357. $post_id = (int) $post_id;
  3358. if ( !$post =& get_post( $post_id ) )
  3359. return false;
  3360. $url = '';
  3361. if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
  3362. if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
  3363. if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
  3364. $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
  3365. elseif ( false !== strpos($file, 'wp-content/uploads') )
  3366. $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
  3367. else
  3368. $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
  3369. }
  3370. }
  3371. if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
  3372. $url = get_the_guid( $post->ID );
  3373. $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
  3374. if ( 'attachment' != $post->post_type || empty( $url ) )
  3375. return false;
  3376. return $url;
  3377. }
  3378. /**
  3379. * Retrieve thumbnail for an attachment.
  3380. *
  3381. * @since 2.1.0
  3382. *
  3383. * @param int $post_id Attachment ID.
  3384. * @return mixed False on failure. Thumbnail file path on success.
  3385. */
  3386. function wp_get_attachment_thumb_file( $post_id = 0 ) {
  3387. $post_id = (int) $post_id;
  3388. if ( !$post =& get_post( $post_id ) )
  3389. return false;
  3390. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
  3391. return false;
  3392. $file = get_attached_file( $post->ID );
  3393. if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
  3394. return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
  3395. return false;
  3396. }
  3397. /**
  3398. * Retrieve URL for an attachment thumbnail.
  3399. *
  3400. * @since 2.1.0
  3401. *
  3402. * @param int $post_id Attachment ID
  3403. * @return string|bool False on failure. Thumbnail URL on success.
  3404. */
  3405. function wp_get_attachment_thumb_url( $post_id = 0 ) {
  3406. $post_id = (int) $post_id;
  3407. if ( !$post =& get_post( $post_id ) )
  3408. return false;
  3409. if ( !$url = wp_get_attachment_url( $post->ID ) )
  3410. return false;
  3411. $sized = image_downsize( $post_id, 'thumbnail' );
  3412. if ( $sized )
  3413. return $sized[0];
  3414. if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
  3415. return false;
  3416. $url = str_replace(basename($url), basename($thumb), $url);
  3417. return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
  3418. }
  3419. /**
  3420. * Check if the attachment is an image.
  3421. *
  3422. * @since 2.1.0
  3423. *
  3424. * @param int $post_id Attachment ID
  3425. * @return bool
  3426. */
  3427. function wp_attachment_is_image( $post_id = 0 ) {
  3428. $post_id = (int) $post_id;
  3429. if ( !$post =& get_post( $post_id ) )
  3430. return false;
  3431. if ( !$file = get_attached_file( $post->ID ) )
  3432. return false;
  3433. $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
  3434. $image_exts = array('jpg', 'jpeg', 'gif', 'png');
  3435. if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
  3436. return true;
  3437. return false;
  3438. }
  3439. /**
  3440. * Retrieve the icon for a MIME type.
  3441. *
  3442. * @since 2.1.0
  3443. *
  3444. * @param string $mime MIME type
  3445. * @return string|bool
  3446. */
  3447. function wp_mime_type_icon( $mime = 0 ) {
  3448. if ( !is_numeric($mime) )
  3449. $icon = wp_cache_get("mime_type_icon_$mime");
  3450. if ( empty($icon) ) {
  3451. $post_id = 0;
  3452. $post_mimes = array();
  3453. if ( is_numeric($mime) ) {
  3454. $mime = (int) $mime;
  3455. if ( $post =& get_post( $mime ) ) {
  3456. $post_id = (int) $post->ID;
  3457. $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
  3458. if ( !empty($ext) ) {
  3459. $post_mimes[] = $ext;
  3460. if ( $ext_type = wp_ext2type( $ext ) )
  3461. $post_mimes[] = $ext_type;
  3462. }
  3463. $mime = $post->post_mime_type;
  3464. } else {
  3465. $mime = 0;
  3466. }
  3467. } else {
  3468. $post_mimes[] = $mime;
  3469. }
  3470. $icon_files = wp_cache_get('icon_files');
  3471. if ( !is_array($icon_files) ) {
  3472. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  3473. $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
  3474. $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
  3475. $icon_files = array();
  3476. while ( $dirs ) {
  3477. $dir = array_shift($keys = array_keys($dirs));
  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 ' 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. Optionaly 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 insterted 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. * Returns a link to a post format index.
  4472. *
  4473. * @since 3.1.0
  4474. *
  4475. * @param $format string Post format
  4476. * @return string Link
  4477. */
  4478. function get_post_format_link( $format ) {
  4479. $term = get_term_by('slug', 'post-format-' . $format, 'post_format' );
  4480. if ( ! $term || is_wp_error( $term ) )
  4481. return false;
  4482. return get_term_link( $term );
  4483. }
  4484. /**
  4485. * Filters the request to allow for the format prefix.
  4486. *
  4487. * @access private
  4488. * @since 3.1.0
  4489. */
  4490. function _post_format_request( $qvs ) {
  4491. if ( ! isset( $qvs['post_format'] ) )
  4492. return $qvs;
  4493. $slugs = get_post_format_slugs();
  4494. if ( isset( $slugs[ $qvs['post_format'] ] ) )
  4495. $qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ];
  4496. $tax = get_taxonomy( 'post_format' );
  4497. $qvs['post_type'] = $tax->object_type;
  4498. return $qvs;
  4499. }
  4500. add_filter( 'request', '_post_format_request' );
  4501. /**
  4502. * Filters the post format term link to remove the format prefix.
  4503. *
  4504. * @access private
  4505. * @since 3.1.0
  4506. */
  4507. function _post_format_link( $link, $term, $taxonomy ) {
  4508. global $wp_rewrite;
  4509. if ( 'post_format' != $taxonomy )
  4510. return $link;
  4511. if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) {
  4512. return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link );
  4513. } else {
  4514. $link = remove_query_arg( 'post_format', $link );
  4515. return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link );
  4516. }
  4517. }
  4518. add_filter( 'term_link', '_post_format_link', 10, 3 );
  4519. /**
  4520. * Remove the post format prefix from the name property of the term object created by get_term().
  4521. *
  4522. * @access private
  4523. * @since 3.1.0
  4524. */
  4525. function _post_format_get_term( $term ) {
  4526. if ( isset( $term->slug ) ) {
  4527. $term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4528. }
  4529. return $term;
  4530. }
  4531. add_filter( 'get_post_format', '_post_format_get_term' );
  4532. /**
  4533. * Remove the post format prefix from the name property of the term objects created by get_terms().
  4534. *
  4535. * @access private
  4536. * @since 3.1.0
  4537. */
  4538. function _post_format_get_terms( $terms, $taxonomies, $args ) {
  4539. if ( in_array( 'post_format', (array) $taxonomies ) ) {
  4540. if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) {
  4541. foreach( $terms as $order => $name ) {
  4542. $terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) );
  4543. }
  4544. } else {
  4545. foreach ( (array) $terms as $order => $term ) {
  4546. if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
  4547. $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4548. }
  4549. }
  4550. }
  4551. }
  4552. return $terms;
  4553. }
  4554. add_filter( 'get_terms', '_post_format_get_terms', 10, 3 );
  4555. /**
  4556. * Remove the post format prefix from the name property of the term objects created by wp_get_object_terms().
  4557. *
  4558. * @access private
  4559. * @since 3.1.0
  4560. */
  4561. function _post_format_wp_get_object_terms( $terms ) {
  4562. foreach ( (array) $terms as $order => $term ) {
  4563. if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
  4564. $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
  4565. }
  4566. }
  4567. return $terms;
  4568. }
  4569. add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' );
  4570. ?>