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