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