Make WordPress Core

source: tags/5.4/src/wp-includes/post.php

Last change on this file was 47394, checked in by johnbillion, 4 years ago

Docs: Correct and improve the docs for some media related functions.

See #48303

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