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