WordPress.org

Make WordPress Core

Changeset 33759


Ignore:
Timestamp:
08/26/2015 12:39:07 PM (6 years ago)
Author:
wonderboymusic
Message:

Posts: move WP_Post into its own file. post.php loads the new files, so this is 100% BC if someone is loading post.php directly. New files created using svn cp.

Creates:
class-wp-post.php
post-functions.php

post.php contains only top-level code. Class file only contains the class. Functions file only contains functions.

See #33413.

Location:
trunk/src/wp-includes
Files:
1 edited
2 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-post.php

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

    r33758 r33759  
    455455
    456456    return $_post;
    457 }
    458 
    459 /**
    460  * WordPress Post class.
    461  *
    462  * @since 3.5.0
    463  *
    464  * @property string $page_template
    465  *
    466  * @property-read array  $ancestors
    467  * @property-read int    $post_category
    468  * @property-read string $tag_input
    469  *
    470  */
    471 final class WP_Post {
    472 
    473     /**
    474      * Post ID.
    475      *
    476      * @var int
    477      */
    478     public $ID;
    479 
    480     /**
    481      * ID of post author.
    482      *
    483      * A numeric string, for compatibility reasons.
    484      *
    485      * @var string
    486      */
    487     public $post_author = 0;
    488 
    489     /**
    490      * The post's local publication time.
    491      *
    492      * @var string
    493      */
    494     public $post_date = '0000-00-00 00:00:00';
    495 
    496     /**
    497      * The post's GMT publication time.
    498      *
    499      * @var string
    500      */
    501     public $post_date_gmt = '0000-00-00 00:00:00';
    502 
    503     /**
    504      * The post's content.
    505      *
    506      * @var string
    507      */
    508     public $post_content = '';
    509 
    510     /**
    511      * The post's title.
    512      *
    513      * @var string
    514      */
    515     public $post_title = '';
    516 
    517     /**
    518      * The post's excerpt.
    519      *
    520      * @var string
    521      */
    522     public $post_excerpt = '';
    523 
    524     /**
    525      * The post's status.
    526      *
    527      * @var string
    528      */
    529     public $post_status = 'publish';
    530 
    531     /**
    532      * Whether comments are allowed.
    533      *
    534      * @var string
    535      */
    536     public $comment_status = 'open';
    537 
    538     /**
    539      * Whether pings are allowed.
    540      *
    541      * @var string
    542      */
    543     public $ping_status = 'open';
    544 
    545     /**
    546      * The post's password in plain text.
    547      *
    548      * @var string
    549      */
    550     public $post_password = '';
    551 
    552     /**
    553      * The post's slug.
    554      *
    555      * @var string
    556      */
    557     public $post_name = '';
    558 
    559     /**
    560      * URLs queued to be pinged.
    561      *
    562      * @var string
    563      */
    564     public $to_ping = '';
    565 
    566     /**
    567      * URLs that have been pinged.
    568      *
    569      * @var string
    570      */
    571     public $pinged = '';
    572 
    573     /**
    574      * The post's local modified time.
    575      *
    576      * @var string
    577      */
    578     public $post_modified = '0000-00-00 00:00:00';
    579 
    580     /**
    581      * The post's GMT modified time.
    582      *
    583      * @var string
    584      */
    585     public $post_modified_gmt = '0000-00-00 00:00:00';
    586 
    587     /**
    588      * A utility DB field for post content.
    589      *
    590      *
    591      * @var string
    592      */
    593     public $post_content_filtered = '';
    594 
    595     /**
    596      * ID of a post's parent post.
    597      *
    598      * @var int
    599      */
    600     public $post_parent = 0;
    601 
    602     /**
    603      * The unique identifier for a post, not necessarily a URL, used as the feed GUID.
    604      *
    605      * @var string
    606      */
    607     public $guid = '';
    608 
    609     /**
    610      * A field used for ordering posts.
    611      *
    612      * @var int
    613      */
    614     public $menu_order = 0;
    615 
    616     /**
    617      * The post's type, like post or page.
    618      *
    619      * @var string
    620      */
    621     public $post_type = 'post';
    622 
    623     /**
    624      * An attachment's mime type.
    625      *
    626      * @var string
    627      */
    628     public $post_mime_type = '';
    629 
    630     /**
    631      * Cached comment count.
    632      *
    633      * A numeric string, for compatibility reasons.
    634      *
    635      * @var string
    636      */
    637     public $comment_count = 0;
    638 
    639     /**
    640      * Stores the post object's sanitization level.
    641      *
    642      * Does not correspond to a DB field.
    643      *
    644      * @var string
    645      */
    646     public $filter;
    647 
    648     /**
    649      * Retrieve WP_Post instance.
    650      *
    651      * @static
    652      * @access public
    653      *
    654      * @global wpdb $wpdb
    655      *
    656      * @param int $post_id Post ID.
    657      * @return WP_Post|false Post object, false otherwise.
    658      */
    659     public static function get_instance( $post_id ) {
    660         global $wpdb;
    661 
    662         $post_id = (int) $post_id;
    663         if ( ! $post_id )
    664             return false;
    665 
    666         $_post = wp_cache_get( $post_id, 'posts' );
    667 
    668         if ( ! $_post ) {
    669             $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
    670 
    671             if ( ! $_post )
    672                 return false;
    673 
    674             $_post = sanitize_post( $_post, 'raw' );
    675             wp_cache_add( $_post->ID, $_post, 'posts' );
    676         } elseif ( empty( $_post->filter ) ) {
    677             $_post = sanitize_post( $_post, 'raw' );
    678         }
    679 
    680         return new WP_Post( $_post );
    681     }
    682 
    683     /**
    684      * Constructor.
    685      *
    686      * @param WP_Post|object $post Post object.
    687      */
    688     public function __construct( $post ) {
    689         foreach ( get_object_vars( $post ) as $key => $value )
    690             $this->$key = $value;
    691     }
    692 
    693     /**
    694      * Isset-er.
    695      *
    696      * @param string $key Property to check if set.
    697      * @return bool
    698      */
    699     public function __isset( $key ) {
    700         if ( 'ancestors' == $key )
    701             return true;
    702 
    703         if ( 'page_template' == $key )
    704             return ( 'page' == $this->post_type );
    705 
    706         if ( 'post_category' == $key )
    707            return true;
    708 
    709         if ( 'tags_input' == $key )
    710            return true;
    711 
    712         return metadata_exists( 'post', $this->ID, $key );
    713     }
    714 
    715     /**
    716      * Getter.
    717      *
    718      * @param string $key Key to get.
    719      * @return mixed
    720      */
    721     public function __get( $key ) {
    722         if ( 'page_template' == $key && $this->__isset( $key ) ) {
    723             return get_post_meta( $this->ID, '_wp_page_template', true );
    724         }
    725 
    726         if ( 'post_category' == $key ) {
    727             if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
    728                 $terms = get_the_terms( $this, 'category' );
    729 
    730             if ( empty( $terms ) )
    731                 return array();
    732 
    733             return wp_list_pluck( $terms, 'term_id' );
    734         }
    735 
    736         if ( 'tags_input' == $key ) {
    737             if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
    738                 $terms = get_the_terms( $this, 'post_tag' );
    739 
    740             if ( empty( $terms ) )
    741                 return array();
    742 
    743             return wp_list_pluck( $terms, 'name' );
    744         }
    745 
    746         // Rest of the values need filtering.
    747         if ( 'ancestors' == $key )
    748             $value = get_post_ancestors( $this );
    749         else
    750             $value = get_post_meta( $this->ID, $key, true );
    751 
    752         if ( $this->filter )
    753             $value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
    754 
    755         return $value;
    756     }
    757 
    758     /**
    759      * {@Missing Summary}
    760      *
    761      * @param string $filter Filter.
    762      * @return self|array|bool|object|WP_Post
    763      */
    764     public function filter( $filter ) {
    765         if ( $this->filter == $filter )
    766             return $this;
    767 
    768         if ( $filter == 'raw' )
    769             return self::get_instance( $this->ID );
    770 
    771         return sanitize_post( $this, $filter );
    772     }
    773 
    774     /**
    775      * Convert object to array.
    776      *
    777      * @return array Object as array.
    778      */
    779     public function to_array() {
    780         $post = get_object_vars( $this );
    781 
    782         foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
    783             if ( $this->__isset( $key ) )
    784                 $post[ $key ] = $this->__get( $key );
    785         }
    786 
    787         return $post;
    788     }
    789457}
    790458
  • trunk/src/wp-includes/post.php

    r33734 r33759  
    88 */
    99
    10 //
    11 // Post Type Registration
    12 //
    13 
    14 /**
    15  * Creates the initial post types when 'init' action is fired.
    16  *
    17  * @since 2.9.0
    18  */
    19 function create_initial_post_types() {
    20     register_post_type( 'post', array(
    21         'labels' => array(
    22             'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
    23         ),
    24         'public'  => true,
    25         '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
    26         '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
    27         'capability_type' => 'post',
    28         'map_meta_cap' => true,
    29         'menu_position' => 5,
    30         'hierarchical' => false,
    31         'rewrite' => false,
    32         'query_var' => false,
    33         'delete_with_user' => true,
    34         'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
    35     ) );
    36 
    37     register_post_type( 'page', array(
    38         'labels' => array(
    39             'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
    40         ),
    41         'public' => true,
    42         'publicly_queryable' => false,
    43         '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
    44         '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
    45         'capability_type' => 'page',
    46         'map_meta_cap' => true,
    47         'menu_position' => 20,
    48         'hierarchical' => true,
    49         'rewrite' => false,
    50         'query_var' => false,
    51         'delete_with_user' => true,
    52         'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
    53     ) );
    54 
    55     register_post_type( 'attachment', array(
    56         'labels' => array(
    57             'name' => _x('Media', 'post type general name'),
    58             'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
    59             'add_new' => _x( 'Add New', 'add new media' ),
    60             'edit_item' => __( 'Edit Media' ),
    61             'view_item' => __( 'View Attachment Page' ),
    62         ),
    63         'public' => true,
    64         'show_ui' => true,
    65         '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
    66         '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
    67         'capability_type' => 'post',
    68         'capabilities' => array(
    69             'create_posts' => 'upload_files',
    70         ),
    71         'map_meta_cap' => true,
    72         'hierarchical' => false,
    73         'rewrite' => false,
    74         'query_var' => false,
    75         'show_in_nav_menus' => false,
    76         'delete_with_user' => true,
    77         'supports' => array( 'title', 'author', 'comments' ),
    78     ) );
    79     add_post_type_support( 'attachment:audio', 'thumbnail' );
    80     add_post_type_support( 'attachment:video', 'thumbnail' );
    81 
    82     register_post_type( 'revision', array(
    83         'labels' => array(
    84             'name' => __( 'Revisions' ),
    85             'singular_name' => __( 'Revision' ),
    86         ),
    87         'public' => false,
    88         '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
    89         '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
    90         'capability_type' => 'post',
    91         'map_meta_cap' => true,
    92         'hierarchical' => false,
    93         'rewrite' => false,
    94         'query_var' => false,
    95         'can_export' => false,
    96         'delete_with_user' => true,
    97         'supports' => array( 'author' ),
    98     ) );
    99 
    100     register_post_type( 'nav_menu_item', array(
    101         'labels' => array(
    102             'name' => __( 'Navigation Menu Items' ),
    103             'singular_name' => __( 'Navigation Menu Item' ),
    104         ),
    105         'public' => false,
    106         '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
    107         'hierarchical' => false,
    108         'rewrite' => false,
    109         'delete_with_user' => false,
    110         'query_var' => false,
    111     ) );
    112 
    113     register_post_status( 'publish', array(
    114         'label'       => _x( 'Published', 'post' ),
    115         'public'      => true,
    116         '_builtin'    => true, /* internal use only. */
    117         'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
    118     ) );
    119 
    120     register_post_status( 'future', array(
    121         'label'       => _x( 'Scheduled', 'post' ),
    122         'protected'   => true,
    123         '_builtin'    => true, /* internal use only. */
    124         'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
    125     ) );
    126 
    127     register_post_status( 'draft', array(
    128         'label'       => _x( 'Draft', 'post' ),
    129         'protected'   => true,
    130         '_builtin'    => true, /* internal use only. */
    131         'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
    132     ) );
    133 
    134     register_post_status( 'pending', array(
    135         'label'       => _x( 'Pending', 'post' ),
    136         'protected'   => true,
    137         '_builtin'    => true, /* internal use only. */
    138         'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
    139     ) );
    140 
    141     register_post_status( 'private', array(
    142         'label'       => _x( 'Private', 'post' ),
    143         'private'     => true,
    144         '_builtin'    => true, /* internal use only. */
    145         'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
    146     ) );
    147 
    148     register_post_status( 'trash', array(
    149         'label'       => _x( 'Trash', 'post' ),
    150         'internal'    => true,
    151         '_builtin'    => true, /* internal use only. */
    152         'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
    153         'show_in_admin_status_list' => true,
    154     ) );
    155 
    156     register_post_status( 'auto-draft', array(
    157         'label'    => 'auto-draft',
    158         'internal' => true,
    159         '_builtin' => true, /* internal use only. */
    160     ) );
    161 
    162     register_post_status( 'inherit', array(
    163         'label'    => 'inherit',
    164         'internal' => true,
    165         '_builtin' => true, /* internal use only. */
    166         'exclude_from_search' => false,
    167     ) );
    168 }
    169 
    170 /**
    171  * Retrieve attached file path based on attachment ID.
    172  *
    173  * By default the path will go through the 'get_attached_file' filter, but
    174  * passing a true to the $unfiltered argument of get_attached_file() will
    175  * return the file path unfiltered.
    176  *
    177  * The function works by getting the single post meta name, named
    178  * '_wp_attached_file' and returning it. This is a convenience function to
    179  * prevent looking up the meta name and provide a mechanism for sending the
    180  * attached filename through a filter.
    181  *
    182  * @since 2.0.0
    183  *
    184  * @param int  $attachment_id Attachment ID.
    185  * @param bool $unfiltered    Optional. Whether to apply filters. Default false.
    186  * @return string|false The file path to where the attached file should be, false otherwise.
    187  */
    188 function get_attached_file( $attachment_id, $unfiltered = false ) {
    189     $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
    190     // If the file is relative, prepend upload dir.
    191     if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
    192         $file = $uploads['basedir'] . "/$file";
    193     if ( $unfiltered )
    194         return $file;
    195 
    196     /**
    197      * Filter the attached file based on the given ID.
    198      *
    199      * @since 2.1.0
    200      *
    201      * @param string $file          Path to attached file.
    202      * @param int    $attachment_id Attachment ID.
    203      */
    204     return apply_filters( 'get_attached_file', $file, $attachment_id );
    205 }
    206 
    207 /**
    208  * Update attachment file path based on attachment ID.
    209  *
    210  * Used to update the file path of the attachment, which uses post meta name
    211  * '_wp_attached_file' to store the path of the attachment.
    212  *
    213  * @since 2.1.0
    214  *
    215  * @param int    $attachment_id Attachment ID.
    216  * @param string $file          File path for the attachment.
    217  * @return bool True on success, false on failure.
    218  */
    219 function update_attached_file( $attachment_id, $file ) {
    220     if ( !get_post( $attachment_id ) )
    221         return false;
    222 
    223     /**
    224      * Filter the path to the attached file to update.
    225      *
    226      * @since 2.1.0
    227      *
    228      * @param string $file          Path to the attached file to update.
    229      * @param int    $attachment_id Attachment ID.
    230      */
    231     $file = apply_filters( 'update_attached_file', $file, $attachment_id );
    232 
    233     if ( $file = _wp_relative_upload_path( $file ) )
    234         return update_post_meta( $attachment_id, '_wp_attached_file', $file );
    235     else
    236         return delete_post_meta( $attachment_id, '_wp_attached_file' );
    237 }
    238 
    239 /**
    240  * Return relative path to an uploaded file.
    241  *
    242  * The path is relative to the current upload dir.
    243  *
    244  * @since 2.9.0
    245  *
    246  * @param string $path Full path to the file.
    247  * @return string Relative path on success, unchanged path on failure.
    248  */
    249 function _wp_relative_upload_path( $path ) {
    250     $new_path = $path;
    251 
    252     $uploads = wp_upload_dir();
    253     if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
    254             $new_path = str_replace( $uploads['basedir'], '', $new_path );
    255             $new_path = ltrim( $new_path, '/' );
    256     }
    257 
    258     /**
    259      * Filter the relative path to an uploaded file.
    260      *
    261      * @since 2.9.0
    262      *
    263      * @param string $new_path Relative path to the file.
    264      * @param string $path     Full path to the file.
    265      */
    266     return apply_filters( '_wp_relative_upload_path', $new_path, $path );
    267 }
    268 
    269 /**
    270  * Retrieve all children of the post parent ID.
    271  *
    272  * Normally, without any enhancements, the children would apply to pages. In the
    273  * context of the inner workings of WordPress, pages, posts, and attachments
    274  * share the same table, so therefore the functionality could apply to any one
    275  * of them. It is then noted that while this function does not work on posts, it
    276  * does not mean that it won't work on posts. It is recommended that you know
    277  * what context you wish to retrieve the children of.
    278  *
    279  * Attachments may also be made the child of a post, so if that is an accurate
    280  * statement (which needs to be verified), it would then be possible to get
    281  * all of the attachments for a post. Attachments have since changed since
    282  * version 2.5, so this is most likely unaccurate, but serves generally as an
    283  * example of what is possible.
    284  *
    285  * The arguments listed as defaults are for this function and also of the
    286  * {@link get_posts()} function. The arguments are combined with the
    287  * get_children defaults and are then passed to the {@link get_posts()}
    288  * function, which accepts additional arguments. You can replace the defaults in
    289  * this function, listed below and the additional arguments listed in the
    290  * {@link get_posts()} function.
    291  *
    292  * The 'post_parent' is the most important argument and important attention
    293  * needs to be paid to the $args parameter. If you pass either an object or an
    294  * integer (number), then just the 'post_parent' is grabbed and everything else
    295  * is lost. If you don't specify any arguments, then it is assumed that you are
    296  * in The Loop and the post parent will be grabbed for from the current post.
    297  *
    298  * The 'post_parent' argument is the ID to get the children. The 'numberposts'
    299  * is the amount of posts to retrieve that has a default of '-1', which is
    300  * used to get all of the posts. Giving a number higher than 0 will only
    301  * retrieve that amount of posts.
    302  *
    303  * The 'post_type' and 'post_status' arguments can be used to choose what
    304  * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
    305  * post types are 'post', 'pages', and 'attachments'. The 'post_status'
    306  * argument will accept any post status within the write administration panels.
    307  *
    308  * @since 2.0.0
    309  *
    310  * @see get_posts()
    311  * @todo Check validity of description.
    312  *
    313  * @global WP_Post $post
    314  *
    315  * @param mixed  $args   Optional. User defined arguments for replacing the defaults. Default empty.
    316  * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
    317  *                       Default OBJECT.
    318  * @return array Array of children, where the type of each element is determined by $output parameter.
    319  *               Empty array on failure.
    320  */
    321 function get_children( $args = '', $output = OBJECT ) {
    322     $kids = array();
    323     if ( empty( $args ) ) {
    324         if ( isset( $GLOBALS['post'] ) ) {
    325             $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
    326         } else {
    327             return $kids;
    328         }
    329     } elseif ( is_object( $args ) ) {
    330         $args = array('post_parent' => (int) $args->post_parent );
    331     } elseif ( is_numeric( $args ) ) {
    332         $args = array('post_parent' => (int) $args);
    333     }
    334 
    335     $defaults = array(
    336         'numberposts' => -1, 'post_type' => 'any',
    337         'post_status' => 'any', 'post_parent' => 0,
    338     );
    339 
    340     $r = wp_parse_args( $args, $defaults );
    341 
    342     $children = get_posts( $r );
    343 
    344     if ( ! $children )
    345         return $kids;
    346 
    347     if ( ! empty( $r['fields'] ) )
    348         return $children;
    349 
    350     update_post_cache($children);
    351 
    352     foreach ( $children as $key => $child )
    353         $kids[$child->ID] = $children[$key];
    354 
    355     if ( $output == OBJECT ) {
    356         return $kids;
    357     } elseif ( $output == ARRAY_A ) {
    358         $weeuns = array();
    359         foreach ( (array) $kids as $kid ) {
    360             $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
    361         }
    362         return $weeuns;
    363     } elseif ( $output == ARRAY_N ) {
    364         $babes = array();
    365         foreach ( (array) $kids as $kid ) {
    366             $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
    367         }
    368         return $babes;
    369     } else {
    370         return $kids;
    371     }
    372 }
    373 
    374 /**
    375  * Get extended entry info (<!--more-->).
    376  *
    377  * There should not be any space after the second dash and before the word
    378  * 'more'. There can be text or space(s) after the word 'more', but won't be
    379  * referenced.
    380  *
    381  * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
    382  * the `<!--more-->`. The 'extended' key has the content after the
    383  * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
    384  *
    385  * @since 1.0.0
    386