home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / post.php < prev    next >
Encoding:
PHP Script  |  2018-01-23  |  210.6 KB  |  6,349 lines

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