You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

6220 lines
206 KiB

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