web/wp-includes/post.php
changeset 194 32102edaa81b
parent 136 bde1974c263b
child 204 09a1c134465b
equal deleted inserted replaced
193:2f6f6f7551ca 194:32102edaa81b
    11 // Post Type Registration
    11 // Post Type Registration
    12 //
    12 //
    13 
    13 
    14 /**
    14 /**
    15  * Creates the initial post types when 'init' action is fired.
    15  * Creates the initial post types when 'init' action is fired.
       
    16  *
       
    17  * @since 2.9.0
    16  */
    18  */
    17 function create_initial_post_types() {
    19 function create_initial_post_types() {
    18 	register_post_type( 'post', array('exclude_from_search' => false) );
    20 	register_post_type( 'post', array(
    19 	register_post_type( 'page', array('exclude_from_search' => false) );
    21 		'labels' => array(
    20 	register_post_type( 'attachment', array('exclude_from_search' => false) );
    22 			'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
    21 	register_post_type( 'revision', array('exclude_from_search' => true) );
    23 		),
       
    24 		'public'  => true,
       
    25 		'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
       
    26 		'_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
       
    27 		'capability_type' => 'post',
       
    28 		'map_meta_cap' => true,
       
    29 		'hierarchical' => false,
       
    30 		'rewrite' => false,
       
    31 		'query_var' => false,
       
    32 		'delete_with_user' => true,
       
    33 		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
       
    34 	) );
       
    35 
       
    36 	register_post_type( 'page', array(
       
    37 		'labels' => array(
       
    38 			'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
       
    39 		),
       
    40 		'public' => true,
       
    41 		'publicly_queryable' => false,
       
    42 		'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
       
    43 		'_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
       
    44 		'capability_type' => 'page',
       
    45 		'map_meta_cap' => true,
       
    46 		'hierarchical' => true,
       
    47 		'rewrite' => false,
       
    48 		'query_var' => false,
       
    49 		'delete_with_user' => true,
       
    50 		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
       
    51 	) );
       
    52 
       
    53 	register_post_type( 'attachment', array(
       
    54 		'labels' => array(
       
    55 			'name' => __( 'Media' ),
       
    56 			'edit_item' => __( 'Edit Media' ),
       
    57 		),
       
    58 		'public' => true,
       
    59 		'show_ui' => false,
       
    60 		'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
       
    61 		'_edit_link' => 'media.php?attachment_id=%d', /* internal use only. don't use this when registering your own post type. */
       
    62 		'capability_type' => 'post',
       
    63 		'map_meta_cap' => true,
       
    64 		'hierarchical' => false,
       
    65 		'rewrite' => false,
       
    66 		'query_var' => false,
       
    67 		'show_in_nav_menus' => false,
       
    68 		'delete_with_user' => true,
       
    69 		'supports' => array( 'comments', 'author' ),
       
    70 	) );
       
    71 
       
    72 	register_post_type( 'revision', array(
       
    73 		'labels' => array(
       
    74 			'name' => __( 'Revisions' ),
       
    75 			'singular_name' => __( 'Revision' ),
       
    76 		),
       
    77 		'public' => false,
       
    78 		'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
       
    79 		'_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
       
    80 		'capability_type' => 'post',
       
    81 		'map_meta_cap' => true,
       
    82 		'hierarchical' => false,
       
    83 		'rewrite' => false,
       
    84 		'query_var' => false,
       
    85 		'can_export' => false,
       
    86 		'delete_with_user' => true,
       
    87 		'supports' => array( 'author' ),
       
    88 	) );
       
    89 
       
    90 	register_post_type( 'nav_menu_item', array(
       
    91 		'labels' => array(
       
    92 			'name' => __( 'Navigation Menu Items' ),
       
    93 			'singular_name' => __( 'Navigation Menu Item' ),
       
    94 		),
       
    95 		'public' => false,
       
    96 		'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
       
    97 		'hierarchical' => false,
       
    98 		'rewrite' => false,
       
    99 		'delete_with_user' => false,
       
   100 		'query_var' => false,
       
   101 	) );
       
   102 
       
   103 	register_post_status( 'publish', array(
       
   104 		'label'       => _x( 'Published', 'post' ),
       
   105 		'public'      => true,
       
   106 		'_builtin'    => true, /* internal use only. */
       
   107 		'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
       
   108 	) );
       
   109 
       
   110 	register_post_status( 'future', array(
       
   111 		'label'       => _x( 'Scheduled', 'post' ),
       
   112 		'protected'   => true,
       
   113 		'_builtin'    => true, /* internal use only. */
       
   114 		'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
       
   115 	) );
       
   116 
       
   117 	register_post_status( 'draft', array(
       
   118 		'label'       => _x( 'Draft', 'post' ),
       
   119 		'protected'   => true,
       
   120 		'_builtin'    => true, /* internal use only. */
       
   121 		'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
       
   122 	) );
       
   123 
       
   124 	register_post_status( 'pending', array(
       
   125 		'label'       => _x( 'Pending', 'post' ),
       
   126 		'protected'   => true,
       
   127 		'_builtin'    => true, /* internal use only. */
       
   128 		'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
       
   129 	) );
       
   130 
       
   131 	register_post_status( 'private', array(
       
   132 		'label'       => _x( 'Private', 'post' ),
       
   133 		'private'     => true,
       
   134 		'_builtin'    => true, /* internal use only. */
       
   135 		'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
       
   136 	) );
       
   137 
       
   138 	register_post_status( 'trash', array(
       
   139 		'label'       => _x( 'Trash', 'post' ),
       
   140 		'internal'    => true,
       
   141 		'_builtin'    => true, /* internal use only. */
       
   142 		'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
       
   143 		'show_in_admin_status_list' => true,
       
   144 	) );
       
   145 
       
   146 	register_post_status( 'auto-draft', array(
       
   147 		'label'    => 'auto-draft',
       
   148 		'internal' => true,
       
   149 		'_builtin' => true, /* internal use only. */
       
   150 	) );
       
   151 
       
   152 	register_post_status( 'inherit', array(
       
   153 		'label'    => 'inherit',
       
   154 		'internal' => true,
       
   155 		'_builtin' => true, /* internal use only. */
       
   156 		'exclude_from_search' => false,
       
   157 	) );
    22 }
   158 }
    23 add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
   159 add_action( 'init', 'create_initial_post_types', 0 ); // highest priority
    24 
   160 
    25 /**
   161 /**
    26  * Retrieve attached file path based on attachment ID.
   162  * Retrieve attached file path based on attachment ID.
    35  *
   171  *
    36  * @since 2.0.0
   172  * @since 2.0.0
    37  * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
   173  * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
    38  *
   174  *
    39  * @param int $attachment_id Attachment ID.
   175  * @param int $attachment_id Attachment ID.
    40  * @param bool $unfiltered Whether to apply filters or not.
   176  * @param bool $unfiltered Whether to apply filters.
    41  * @return string The file path to the attached file.
   177  * @return string|bool The file path to the attached file, or false if the attachment does not exist.
    42  */
   178  */
    43 function get_attached_file( $attachment_id, $unfiltered = false ) {
   179 function get_attached_file( $attachment_id, $unfiltered = false ) {
    44 	$file = get_post_meta( $attachment_id, '_wp_attached_file', true );
   180 	$file = get_post_meta( $attachment_id, '_wp_attached_file', true );
    45 	// If the file is relative, prepend upload dir
   181 	// If the file is relative, prepend upload dir
    46 	if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
   182 	if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
    47 		$file = $uploads['basedir'] . "/$file";
   183 		$file = $uploads['basedir'] . "/$file";
    48 	if ( $unfiltered )
   184 	if ( $unfiltered )
    49 		return $file;
   185 		return $file;
    50 	return apply_filters( 'get_attached_file', $file, $attachment_id );
   186 	return apply_filters( 'get_attached_file', $file, $attachment_id );
    51 }
   187 }
    76 /**
   212 /**
    77  * Return relative path to an uploaded file.
   213  * Return relative path to an uploaded file.
    78  *
   214  *
    79  * The path is relative to the current upload dir.
   215  * The path is relative to the current upload dir.
    80  *
   216  *
    81  * @since 2.9
   217  * @since 2.9.0
    82  * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
   218  * @uses apply_filters() Calls '_wp_relative_upload_path' on file path.
    83  *
   219  *
    84  * @param string $path Full path to the file
   220  * @param string $path Full path to the file
    85  * @return string relative path on success, unchanged path on failure.
   221  * @return string relative path on success, unchanged path on failure.
    86  */
   222  */
   143  *
   279  *
   144  * @param mixed $args Optional. User defined arguments for replacing the defaults.
   280  * @param mixed $args Optional. User defined arguments for replacing the defaults.
   145  * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
   281  * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
   146  * @return array|bool False on failure and the type will be determined by $output parameter.
   282  * @return array|bool False on failure and the type will be determined by $output parameter.
   147  */
   283  */
   148 function &get_children($args = '', $output = OBJECT) {
   284 function get_children($args = '', $output = OBJECT) {
   149 	$kids = array();
   285 	$kids = array();
   150 	if ( empty( $args ) ) {
   286 	if ( empty( $args ) ) {
   151 		if ( isset( $GLOBALS['post'] ) ) {
   287 		if ( isset( $GLOBALS['post'] ) ) {
   152 			$args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
   288 			$args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
   153 		} else {
   289 		} else {
   172 		return $kids;
   308 		return $kids;
   173 
   309 
   174 	update_post_cache($children);
   310 	update_post_cache($children);
   175 
   311 
   176 	foreach ( $children as $key => $child )
   312 	foreach ( $children as $key => $child )
   177 		$kids[$child->ID] =& $children[$key];
   313 		$kids[$child->ID] = $children[$key];
   178 
   314 
   179 	if ( $output == OBJECT ) {
   315 	if ( $output == OBJECT ) {
   180 		return $kids;
   316 		return $kids;
   181 	} elseif ( $output == ARRAY_A ) {
   317 	} elseif ( $output == ARRAY_A ) {
   182 		foreach ( (array) $kids as $kid )
   318 		foreach ( (array) $kids as $kid )
   196  *
   332  *
   197  * There should not be any space after the second dash and before the word
   333  * There should not be any space after the second dash and before the word
   198  * 'more'. There can be text or space(s) after the word 'more', but won't be
   334  * 'more'. There can be text or space(s) after the word 'more', but won't be
   199  * referenced.
   335  * referenced.
   200  *
   336  *
   201  * The returned array has 'main' and 'extended' keys. Main has the text before
   337  * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
   202  * the <code><!--more--></code>. The 'extended' key has the content after the
   338  * the <code><!--more--></code>. The 'extended' key has the content after the
   203  * <code><!--more--></code> comment.
   339  * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text.
   204  *
   340  *
   205  * @since 1.0.0
   341  * @since 1.0.0
   206  *
   342  *
   207  * @param string $post Post content.
   343  * @param string $post Post content.
   208  * @return array Post before ('main') and after ('extended').
   344  * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text').
   209  */
   345  */
   210 function get_extended($post) {
   346 function get_extended($post) {
   211 	//Match the new style more links
   347 	//Match the new style more links
   212 	if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
   348 	if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
   213 		list($main, $extended) = explode($matches[0], $post, 2);
   349 		list($main, $extended) = explode($matches[0], $post, 2);
       
   350 		$more_text = $matches[1];
   214 	} else {
   351 	} else {
   215 		$main = $post;
   352 		$main = $post;
   216 		$extended = '';
   353 		$extended = '';
       
   354 		$more_text = '';
   217 	}
   355 	}
   218 
   356 
   219 	// Strip leading and trailing whitespace
   357 	// Strip leading and trailing whitespace
   220 	$main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
   358 	$main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
   221 	$extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
   359 	$extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
   222 
   360 	$more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
   223 	return array('main' => $main, 'extended' => $extended);
   361 
       
   362 	return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
   224 }
   363 }
   225 
   364 
   226 /**
   365 /**
   227  * Retrieves post data given a post ID or post object.
   366  * Retrieves post data given a post ID or post object.
   228  *
   367  *
   249 			return $null;
   388 			return $null;
   250 	} elseif ( is_object($post) && empty($post->filter) ) {
   389 	} elseif ( is_object($post) && empty($post->filter) ) {
   251 		_get_post_ancestors($post);
   390 		_get_post_ancestors($post);
   252 		$_post = sanitize_post($post, 'raw');
   391 		$_post = sanitize_post($post, 'raw');
   253 		wp_cache_add($post->ID, $_post, 'posts');
   392 		wp_cache_add($post->ID, $_post, 'posts');
       
   393 	} elseif ( is_object($post) && 'raw' == $post->filter ) {
       
   394 		$_post = $post;
   254 	} else {
   395 	} else {
   255 		if ( is_object($post) )
   396 		if ( is_object($post) )
   256 			$post = $post->ID;
   397 			$post_id = $post->ID;
   257 		$post = (int) $post;
   398 		else
   258 		if ( ! $_post = wp_cache_get($post, 'posts') ) {
   399 			$post_id = $post;
   259 			$_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
   400 
       
   401 		$post_id = (int) $post_id;
       
   402 		if ( ! $_post = wp_cache_get($post_id, 'posts') ) {
       
   403 			$_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id));
   260 			if ( ! $_post )
   404 			if ( ! $_post )
   261 				return $null;
   405 				return $null;
   262 			_get_post_ancestors($_post);
   406 			_get_post_ancestors($_post);
   263 			$_post = sanitize_post($_post, 'raw');
   407 			$_post = sanitize_post($_post, 'raw');
   264 			wp_cache_add($_post->ID, $_post, 'posts');
   408 			wp_cache_add($_post->ID, $_post, 'posts');
   290  * @return array Ancestor IDs or empty array if none are found.
   434  * @return array Ancestor IDs or empty array if none are found.
   291  */
   435  */
   292 function get_post_ancestors($post) {
   436 function get_post_ancestors($post) {
   293 	$post = get_post($post);
   437 	$post = get_post($post);
   294 
   438 
   295 	if ( !empty($post->ancestors) )
   439 	if ( ! isset( $post->ancestors ) )
       
   440 		_get_post_ancestors( $post );
       
   441 
       
   442 	if ( ! empty( $post->ancestors ) )
   296 		return $post->ancestors;
   443 		return $post->ancestors;
   297 
   444 
   298 	return array();
   445 	return array();
   299 }
   446 }
   300 
   447 
   301 /**
   448 /**
   302  * Retrieve data from a post field based on Post ID.
   449  * Retrieve data from a post field based on Post ID.
   303  *
   450  *
   304  * Examples of the post field will be, 'post_type', 'post_status', 'content',
   451  * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
   305  * etc and based off of the post object property or key names.
   452  * etc and based off of the post object property or key names.
   306  *
   453  *
   307  * The context values are based off of the taxonomy filter functions and
   454  * The context values are based off of the taxonomy filter functions and
   308  * supported values are found within those functions.
   455  * supported values are found within those functions.
   309  *
   456  *
   350 
   497 
   351 	return false;
   498 	return false;
   352 }
   499 }
   353 
   500 
   354 /**
   501 /**
       
   502  * Retrieve the format slug for a post
       
   503  *
       
   504  * @since 3.1.0
       
   505  *
       
   506  * @param int|object $post A post
       
   507  *
       
   508  * @return mixed The format if successful. False if no format is set. WP_Error if errors.
       
   509  */
       
   510 function get_post_format( $post = null ) {
       
   511 	$post = get_post($post);
       
   512 
       
   513 	if ( ! post_type_supports( $post->post_type, 'post-formats' ) )
       
   514 		return false;
       
   515 
       
   516 	$_format = get_the_terms( $post->ID, 'post_format' );
       
   517 
       
   518 	if ( empty( $_format ) )
       
   519 		return false;
       
   520 
       
   521 	$format = array_shift( $_format );
       
   522 
       
   523 	return ( str_replace('post-format-', '', $format->slug ) );
       
   524 }
       
   525 
       
   526 /**
       
   527  * Check if a post has a particular format
       
   528  *
       
   529  * @since 3.1.0
       
   530  * @uses has_term()
       
   531  *
       
   532  * @param string $format The format to check for
       
   533  * @param object|id $post The post to check. If not supplied, defaults to the current post if used in the loop.
       
   534  * @return bool True if the post has the format, false otherwise.
       
   535  */
       
   536 function has_post_format( $format, $post = null ) {
       
   537 	return has_term('post-format-' . sanitize_key($format), 'post_format', $post);
       
   538 }
       
   539 
       
   540 /**
       
   541  * Assign a format to a post
       
   542  *
       
   543  * @since 3.1.0
       
   544  *
       
   545  * @param int|object $post The post for which to assign a format
       
   546  * @param string $format  A format to assign. Use an empty string or array to remove all formats from the post.
       
   547  * @return mixed WP_Error on error. Array of affected term IDs on success.
       
   548  */
       
   549 function set_post_format( $post, $format ) {
       
   550 	$post = get_post($post);
       
   551 
       
   552 	if ( empty($post) )
       
   553 		return new WP_Error('invalid_post', __('Invalid post'));
       
   554 
       
   555 	if ( !empty($format) ) {
       
   556 		$format = sanitize_key($format);
       
   557 		if ( 'standard' == $format || !in_array( $format, array_keys( get_post_format_slugs() ) ) )
       
   558 			$format = '';
       
   559 		else
       
   560 			$format = 'post-format-' . $format;
       
   561 	}
       
   562 
       
   563 	return wp_set_post_terms($post->ID, $format, 'post_format');
       
   564 }
       
   565 
       
   566 /**
   355  * Retrieve the post status based on the Post ID.
   567  * Retrieve the post status based on the Post ID.
   356  *
   568  *
   357  * If the post ID is of an attachment, then the parent post status will be given
   569  * If the post ID is of an attachment, then the parent post status will be given
   358  * instead.
   570  * instead.
   359  *
   571  *
   363  * @return string|bool Post status or false on failure.
   575  * @return string|bool Post status or false on failure.
   364  */
   576  */
   365 function get_post_status($ID = '') {
   577 function get_post_status($ID = '') {
   366 	$post = get_post($ID);
   578 	$post = get_post($ID);
   367 
   579 
   368 	if ( is_object($post) ) {
   580 	if ( !is_object($post) )
   369 		if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
   581 		return false;
       
   582 
       
   583 	if ( 'attachment' == $post->post_type ) {
       
   584 		if ( 'private' == $post->post_status )
       
   585 			return 'private';
       
   586 
       
   587 		// Unattached attachments are assumed to be published
       
   588 		if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
       
   589 			return 'publish';
       
   590 
       
   591 		// Inherit status from the parent
       
   592 		if ( $post->post_parent && ( $post->ID != $post->post_parent ) )
   370 			return get_post_status($post->post_parent);
   593 			return get_post_status($post->post_parent);
   371 		else
   594 	}
   372 			return $post->post_status;
   595 
   373 	}
   596 	return $post->post_status;
   374 
       
   375 	return false;
       
   376 }
   597 }
   377 
   598 
   378 /**
   599 /**
   379  * Retrieve all of the WordPress supported post statuses.
   600  * Retrieve all of the WordPress supported post statuses.
   380  *
   601  *
   415 
   636 
   416 	return $status;
   637 	return $status;
   417 }
   638 }
   418 
   639 
   419 /**
   640 /**
       
   641  * Register a post status. Do not use before init.
       
   642  *
       
   643  * A simple function for creating or modifying a post status based on the
       
   644  * parameters given. The function will accept an array (second optional
       
   645  * parameter), along with a string for the post status name.
       
   646  *
       
   647  *
       
   648  * Optional $args contents:
       
   649  *
       
   650  * label - A descriptive name for the post status marked for translation. Defaults to $post_status.
       
   651  * public - Whether posts of this status should be shown in the front end of the site. Defaults to true.
       
   652  * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false.
       
   653  * show_in_admin_all_list - Whether to include posts in the edit listing for their post type
       
   654  * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit
       
   655  *                             listings, e.g. All (12) | Published (9) | My Custom Status (2) ...
       
   656  *
       
   657  * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
       
   658  *
       
   659  * @package WordPress
       
   660  * @subpackage Post
       
   661  * @since 3.0.0
       
   662  * @uses $wp_post_statuses Inserts new post status object into the list
       
   663  *
       
   664  * @param string $post_status Name of the post status.
       
   665  * @param array|string $args See above description.
       
   666  */
       
   667 function register_post_status($post_status, $args = array()) {
       
   668 	global $wp_post_statuses;
       
   669 
       
   670 	if (!is_array($wp_post_statuses))
       
   671 		$wp_post_statuses = array();
       
   672 
       
   673 	// Args prefixed with an underscore are reserved for internal use.
       
   674 	$defaults = array('label' => false, 'label_count' => false, 'exclude_from_search' => null, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'hierarchical' => false, 'public' => null, 'internal' => null, 'protected' => null, 'private' => null, 'show_in_admin_all' => null, 'publicly_queryable' => null, 'show_in_admin_status_list' => null, 'show_in_admin_all_list' => null, 'single_view_cap' => null);
       
   675 	$args = wp_parse_args($args, $defaults);
       
   676 	$args = (object) $args;
       
   677 
       
   678 	$post_status = sanitize_key($post_status);
       
   679 	$args->name = $post_status;
       
   680 
       
   681 	if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
       
   682 		$args->internal = true;
       
   683 
       
   684 	if ( null === $args->public  )
       
   685 		$args->public = false;
       
   686 
       
   687 	if ( null === $args->private  )
       
   688 		$args->private = false;
       
   689 
       
   690 	if ( null === $args->protected  )
       
   691 		$args->protected = false;
       
   692 
       
   693 	if ( null === $args->internal  )
       
   694 		$args->internal = false;
       
   695 
       
   696 	if ( null === $args->publicly_queryable )
       
   697 		$args->publicly_queryable = $args->public;
       
   698 
       
   699 	if ( null === $args->exclude_from_search )
       
   700 		$args->exclude_from_search = $args->internal;
       
   701 
       
   702 	if ( null === $args->show_in_admin_all_list )
       
   703 		$args->show_in_admin_all_list = !$args->internal;
       
   704 
       
   705 	if ( null === $args->show_in_admin_status_list )
       
   706 			$args->show_in_admin_status_list = !$args->internal;
       
   707 
       
   708 	if ( null === $args->single_view_cap )
       
   709 		$args->single_view_cap = $args->public ? '' : 'edit';
       
   710 
       
   711 	if ( false === $args->label )
       
   712 		$args->label = $post_status;
       
   713 
       
   714 	if ( false === $args->label_count )
       
   715 		$args->label_count = array( $args->label, $args->label );
       
   716 
       
   717 	$wp_post_statuses[$post_status] = $args;
       
   718 
       
   719 	return $args;
       
   720 }
       
   721 
       
   722 /**
       
   723  * Retrieve a post status object by name
       
   724  *
       
   725  * @package WordPress
       
   726  * @subpackage Post
       
   727  * @since 3.0.0
       
   728  * @uses $wp_post_statuses
       
   729  * @see register_post_status
       
   730  * @see get_post_statuses
       
   731  *
       
   732  * @param string $post_status The name of a registered post status
       
   733  * @return object A post status object
       
   734  */
       
   735 function get_post_status_object( $post_status ) {
       
   736 	global $wp_post_statuses;
       
   737 
       
   738 	if ( empty($wp_post_statuses[$post_status]) )
       
   739 		return null;
       
   740 
       
   741 	return $wp_post_statuses[$post_status];
       
   742 }
       
   743 
       
   744 /**
       
   745  * Get a list of all registered post status objects.
       
   746  *
       
   747  * @package WordPress
       
   748  * @subpackage Post
       
   749  * @since 3.0.0
       
   750  * @uses $wp_post_statuses
       
   751  * @see register_post_status
       
   752  * @see get_post_status_object
       
   753  *
       
   754  * @param array|string $args An array of key => value arguments to match against the post status objects.
       
   755  * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
       
   756  * @param string $operator The logical operation to perform. 'or' means only one element
       
   757  *  from the array needs to match; 'and' means all elements must match. The default is 'and'.
       
   758  * @return array A list of post status names or objects
       
   759  */
       
   760 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
       
   761 	global $wp_post_statuses;
       
   762 
       
   763 	$field = ('names' == $output) ? 'name' : false;
       
   764 
       
   765 	return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
       
   766 }
       
   767 
       
   768 /**
       
   769  * Whether the post type is hierarchical.
       
   770  *
       
   771  * A false return value might also mean that the post type does not exist.
       
   772  *
       
   773  * @since 3.0.0
       
   774  * @see get_post_type_object
       
   775  *
       
   776  * @param string $post_type Post type name
       
   777  * @return bool Whether post type is hierarchical.
       
   778  */
       
   779 function is_post_type_hierarchical( $post_type ) {
       
   780 	if ( ! post_type_exists( $post_type ) )
       
   781 		return false;
       
   782 
       
   783 	$post_type = get_post_type_object( $post_type );
       
   784 	return $post_type->hierarchical;
       
   785 }
       
   786 
       
   787 /**
       
   788  * Checks if a post type is registered.
       
   789  *
       
   790  * @since 3.0.0
       
   791  * @uses get_post_type_object()
       
   792  *
       
   793  * @param string $post_type Post type name
       
   794  * @return bool Whether post type is registered.
       
   795  */
       
   796 function post_type_exists( $post_type ) {
       
   797 	return (bool) get_post_type_object( $post_type );
       
   798 }
       
   799 
       
   800 /**
   420  * Retrieve the post type of the current post or of a given post.
   801  * Retrieve the post type of the current post or of a given post.
   421  *
   802  *
   422  * @since 2.1.0
   803  * @since 2.1.0
   423  *
   804  *
   424  * @uses $wpdb
   805  * @uses $post The Loop current post global
   425  * @uses $posts The Loop post global
   806  *
   426  *
   807  * @param mixed $the_post Optional. Post object or post ID.
   427  * @param mixed $post Optional. Post object or post ID.
       
   428  * @return bool|string post type or false on failure.
   808  * @return bool|string post type or false on failure.
   429  */
   809  */
   430 function get_post_type($post = false) {
   810 function get_post_type( $the_post = false ) {
   431 	global $posts;
   811 	global $post;
   432 
   812 
   433 	if ( false === $post )
   813 	if ( false === $the_post )
   434 		$post = $posts[0];
   814 		$the_post = $post;
   435 	elseif ( (int) $post )
   815 	elseif ( is_numeric($the_post) )
   436 		$post = get_post($post, OBJECT);
   816 		$the_post = get_post($the_post);
   437 
   817 
   438 	if ( is_object($post) )
   818 	if ( is_object($the_post) )
   439 		return $post->post_type;
   819 		return $the_post->post_type;
   440 
   820 
   441 	return false;
   821 	return false;
       
   822 }
       
   823 
       
   824 /**
       
   825  * Retrieve a post type object by name
       
   826  *
       
   827  * @package WordPress
       
   828  * @subpackage Post
       
   829  * @since 3.0.0
       
   830  * @uses $wp_post_types
       
   831  * @see register_post_type
       
   832  * @see get_post_types
       
   833  *
       
   834  * @param string $post_type The name of a registered post type
       
   835  * @return object A post type object
       
   836  */
       
   837 function get_post_type_object( $post_type ) {
       
   838 	global $wp_post_types;
       
   839 
       
   840 	if ( empty($wp_post_types[$post_type]) )
       
   841 		return null;
       
   842 
       
   843 	return $wp_post_types[$post_type];
   442 }
   844 }
   443 
   845 
   444 /**
   846 /**
   445  * Get a list of all registered post type objects.
   847  * Get a list of all registered post type objects.
   446  *
   848  *
   447  * @package WordPress
   849  * @package WordPress
   448  * @subpackage Post
   850  * @subpackage Post
   449  * @since 2.9.0
   851  * @since 2.9.0
   450  * @uses $wp_post_types
   852  * @uses $wp_post_types
   451  * @see register_post_type
   853  * @see register_post_type
   452  * @see get_post_types
   854  *
   453  *
   855  * @param array|string $args An array of key => value arguments to match against the post type objects.
   454  * @param array|string $args An array of key => value arguments to match against the post types.
       
   455  *  Only post types having attributes that match all arguments are returned.
       
   456  * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
   856  * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
       
   857  * @param string $operator The logical operation to perform. 'or' means only one element
       
   858  *  from the array needs to match; 'and' means all elements must match. The default is 'and'.
   457  * @return array A list of post type names or objects
   859  * @return array A list of post type names or objects
   458  */
   860  */
   459 function get_post_types( $args = array(), $output = 'names' ) {
   861 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
   460 	global $wp_post_types;
   862 	global $wp_post_types;
   461 
   863 
   462 	$do_names = false;
   864 	$field = ('names' == $output) ? 'name' : false;
   463 	if ( 'names' == $output )
   865 
   464 		$do_names = true;
   866 	return wp_filter_object_list($wp_post_types, $args, $operator, $field);
   465 
       
   466 	$post_types = array();
       
   467 	foreach ( (array) $wp_post_types as $post_type ) {
       
   468 		if ( empty($args) ) {
       
   469 			if ( $do_names )
       
   470 				$post_types[] = $post_type->name;
       
   471 			else
       
   472 				$post_types[] = $post_type;
       
   473 		} elseif ( array_intersect_assoc((array) $post_type, $args) ) {
       
   474 			if ( $do_names )
       
   475 				$post_types[] = $post_type->name;
       
   476 			else
       
   477 				$post_types[] = $post_type;
       
   478 		}
       
   479 	}
       
   480 
       
   481 	return $post_types;
       
   482 }
   867 }
   483 
   868 
   484 /**
   869 /**
   485  * Register a post type. Do not use before init.
   870  * Register a post type. Do not use before init.
   486  *
   871  *
   487  * A simple function for creating or modifying a post type based on the
   872  * A function for creating or modifying a post type based on the
   488  * parameters given. The function will accept an array (second optional
   873  * parameters given. The function will accept an array (second optional
   489  * parameter), along with a string for the post type name.
   874  * parameter), along with a string for the post type name.
   490  *
   875  *
   491  *
       
   492  * Optional $args contents:
   876  * Optional $args contents:
   493  *
   877  *
   494  * exclude_from_search - Whether to exclude posts with this post type from search results. Defaults to true.
   878  * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
   495  *
   879  * - labels - An array of labels for this post type.
   496  * @package WordPress
   880  *     * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
   497  * @subpackage Post
   881  *     * You can see accepted values in {@link get_post_type_labels()}.
       
   882  * - description - A short descriptive summary of what the post type is. Defaults to blank.
       
   883  * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
       
   884  *     * Defaults to false.
       
   885  *     * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
       
   886  *       inherited from public, each does not rely on this relationship and controls a very specific intention.
       
   887  * - exclude_from_search - Whether to exclude posts with this post type from front end search results.
       
   888  *     * If not set, the the opposite of public's current value is used.
       
   889  * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
       
   890  *     * ?post_type={post_type_key}
       
   891  *     * ?{post_type_key}={single_post_slug}
       
   892  *     * ?{post_type_query_var}={single_post_slug}
       
   893  *     * If not set, the default is inherited from public.
       
   894  * - show_ui - Whether to generate a default UI for managing this post type in the admin.
       
   895  *     * If not set, the default is inherited from public.
       
   896  * - show_in_nav_menus - Makes this post type available for selection in navigation menus.
       
   897  *     * If not set, the default is inherited from public.
       
   898  * - show_in_menu - Where to show the post type in the admin menu.
       
   899  *     * If true, the post type is shown in its own top level menu.
       
   900  *     * If false, no menu is shown
       
   901  *     * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
       
   902  *       be placed as a sub menu of that.
       
   903  *     * show_ui must be true.
       
   904  *     * If not set, the default is inherited from show_ui
       
   905  * - show_in_admin_bar - Makes this post type available via the admin bar.
       
   906  *     * If not set, the default is inherited from show_in_menu
       
   907  * - menu_position - The position in the menu order the post type should appear.
       
   908  *     * show_in_menu must be true
       
   909  *     * Defaults to null, which places it at the bottom of its area.
       
   910  * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
       
   911  * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
       
   912  *     * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
       
   913  *       capabilities, e.g. array('story', 'stories').
       
   914  * - capabilities - Array of capabilities for this post type.
       
   915  *     * By default the capability_type is used as a base to construct capabilities.
       
   916  *     * You can see accepted values in {@link get_post_type_capabilities()}.
       
   917  * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
       
   918  * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
       
   919  * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
       
   920  *     * See {@link add_post_type_support()} for documentation.
       
   921  * - register_meta_box_cb - Provide a callback function that will be called when setting up the
       
   922  *     meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
       
   923  * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
       
   924  *     * Default is no taxonomies.
       
   925  *     * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
       
   926  * - has_archive - True to enable post type archives. Default is false.
       
   927  *     * Will generate the proper rewrite rules if rewrite is enabled.
       
   928  * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
       
   929  *     * To prevent rewrite, set to false.
       
   930  *     * To specify rewrite rules, an array can be passed with any of these keys
       
   931  *         * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
       
   932  *         * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
       
   933  *         * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
       
   934  *         * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
       
   935  *         * 'ep_mask' => const Assign an endpoint mask.
       
   936  *             * If not specified and permalink_epmask is set, inherits from permalink_epmask.
       
   937  *             * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
       
   938  * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
       
   939  *     * If false, a post type cannot be loaded at ?{query_var}={post_slug}
       
   940  *     * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
       
   941  * - can_export - Allows this post type to be exported. Defaults to true.
       
   942  * - delete_with_user - Whether to delete posts of this type when deleting a user.
       
   943  *     * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
       
   944  *     * If false, posts of this type belonging to the user will *not* be trashed or deleted.
       
   945  *     * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
       
   946  * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
       
   947  * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
       
   948  *
   498  * @since 2.9.0
   949  * @since 2.9.0
   499  * @uses $wp_post_types Inserts new post type object into the list
   950  * @uses $wp_post_types Inserts new post type object into the list
   500  *
   951  *
   501  * @param string $post_type Name of the post type.
   952  * @param string $post_type Post type key, must not exceed 20 characters
   502  * @param array|string $args See above description.
   953  * @param array|string $args See optional args description above.
   503  */
   954  * @return object|WP_Error the registered post type object, or an error object
   504 function register_post_type($post_type, $args = array()) {
   955  */
   505 	global $wp_post_types;
   956 function register_post_type( $post_type, $args = array() ) {
   506 
   957 	global $wp_post_types, $wp_rewrite, $wp;
   507 	if (!is_array($wp_post_types))
   958 
       
   959 	if ( !is_array($wp_post_types) )
   508 		$wp_post_types = array();
   960 		$wp_post_types = array();
   509 
   961 
   510 	$defaults = array('exclude_from_search' => true);
   962 	// Args prefixed with an underscore are reserved for internal use.
       
   963 	$defaults = array(
       
   964 		'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null,
       
   965 		'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null,
       
   966 		'_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false,
       
   967 		'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true,
       
   968 		'supports' => array(), 'register_meta_box_cb' => null,
       
   969 		'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null,
       
   970 		'can_export' => true,
       
   971 		'show_in_nav_menus' => null, 'show_in_menu' => null, 'show_in_admin_bar' => null,
       
   972 		'delete_with_user' => null,
       
   973 	);
   511 	$args = wp_parse_args($args, $defaults);
   974 	$args = wp_parse_args($args, $defaults);
   512 
   975 	$args = (object) $args;
   513 	$post_type = sanitize_user($post_type, true);
   976 
   514 	$args['name'] = $post_type;
   977 	$post_type = sanitize_key($post_type);
   515 	$wp_post_types[$post_type] = (object) $args;
   978 	$args->name = $post_type;
       
   979 
       
   980 	if ( strlen( $post_type ) > 20 )
       
   981 			return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
       
   982 
       
   983 	// If not set, default to the setting for public.
       
   984 	if ( null === $args->publicly_queryable )
       
   985 		$args->publicly_queryable = $args->public;
       
   986 
       
   987 	// If not set, default to the setting for public.
       
   988 	if ( null === $args->show_ui )
       
   989 		$args->show_ui = $args->public;
       
   990 
       
   991 	// If not set, default to the setting for show_ui.
       
   992 	if ( null === $args->show_in_menu || ! $args->show_ui )
       
   993 		$args->show_in_menu = $args->show_ui;
       
   994 
       
   995 	// If not set, default to the whether the full UI is shown.
       
   996 	if ( null === $args->show_in_admin_bar )
       
   997 		$args->show_in_admin_bar = true === $args->show_in_menu;
       
   998 
       
   999 	// Whether to show this type in nav-menus.php. Defaults to the setting for public.
       
  1000 	if ( null === $args->show_in_nav_menus )
       
  1001 		$args->show_in_nav_menus = $args->public;
       
  1002 
       
  1003 	// If not set, default to true if not public, false if public.
       
  1004 	if ( null === $args->exclude_from_search )
       
  1005 		$args->exclude_from_search = !$args->public;
       
  1006 
       
  1007 	// Back compat with quirky handling in version 3.0. #14122
       
  1008 	if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
       
  1009 		$args->map_meta_cap = true;
       
  1010 
       
  1011 	if ( null === $args->map_meta_cap )
       
  1012 		$args->map_meta_cap = false;
       
  1013 
       
  1014 	$args->cap = get_post_type_capabilities( $args );
       
  1015 	unset($args->capabilities);
       
  1016 
       
  1017 	if ( is_array( $args->capability_type ) )
       
  1018 		$args->capability_type = $args->capability_type[0];
       
  1019 
       
  1020 	if ( ! empty($args->supports) ) {
       
  1021 		add_post_type_support($post_type, $args->supports);
       
  1022 		unset($args->supports);
       
  1023 	} else {
       
  1024 		// Add default features
       
  1025 		add_post_type_support($post_type, array('title', 'editor'));
       
  1026 	}
       
  1027 
       
  1028 	if ( false !== $args->query_var && !empty($wp) ) {
       
  1029 		if ( true === $args->query_var )
       
  1030 			$args->query_var = $post_type;
       
  1031 		$args->query_var = sanitize_title_with_dashes($args->query_var);
       
  1032 		$wp->add_query_var($args->query_var);
       
  1033 	}
       
  1034 
       
  1035 	if ( false !== $args->rewrite && ( is_admin() || '' != get_option('permalink_structure') ) ) {
       
  1036 		if ( ! is_array( $args->rewrite ) )
       
  1037 			$args->rewrite = array();
       
  1038 		if ( empty( $args->rewrite['slug'] ) )
       
  1039 			$args->rewrite['slug'] = $post_type;
       
  1040 		if ( ! isset( $args->rewrite['with_front'] ) )
       
  1041 			$args->rewrite['with_front'] = true;
       
  1042 		if ( ! isset( $args->rewrite['pages'] ) )
       
  1043 			$args->rewrite['pages'] = true;
       
  1044 		if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
       
  1045 			$args->rewrite['feeds'] = (bool) $args->has_archive;
       
  1046 		if ( ! isset( $args->rewrite['ep_mask'] ) ) {
       
  1047 			if ( isset( $args->permalink_epmask ) )
       
  1048 				$args->rewrite['ep_mask'] = $args->permalink_epmask;
       
  1049 			else
       
  1050 				$args->rewrite['ep_mask'] = EP_PERMALINK;
       
  1051 		}
       
  1052 
       
  1053 		if ( $args->hierarchical )
       
  1054 			add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
       
  1055 		else
       
  1056 			add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=");
       
  1057 
       
  1058 		if ( $args->has_archive ) {
       
  1059 			$archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
       
  1060 			if ( $args->rewrite['with_front'] )
       
  1061 				$archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
       
  1062 			else
       
  1063 				$archive_slug = $wp_rewrite->root . $archive_slug;
       
  1064 
       
  1065 			add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
       
  1066 			if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
       
  1067 				$feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
       
  1068 				add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
       
  1069 				add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
       
  1070 			}
       
  1071 			if ( $args->rewrite['pages'] )
       
  1072 				add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
       
  1073 		}
       
  1074 
       
  1075 		add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite );
       
  1076 	}
       
  1077 
       
  1078 	if ( $args->register_meta_box_cb )
       
  1079 		add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1);
       
  1080 
       
  1081 	$args->labels = get_post_type_labels( $args );
       
  1082 	$args->label = $args->labels->name;
       
  1083 
       
  1084 	$wp_post_types[$post_type] = $args;
       
  1085 
       
  1086 	add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
       
  1087 
       
  1088 	foreach ( $args->taxonomies as $taxonomy ) {
       
  1089 		register_taxonomy_for_object_type( $taxonomy, $post_type );
       
  1090 	}
       
  1091 
       
  1092 	do_action( 'registered_post_type', $post_type, $args );
       
  1093 
       
  1094 	return $args;
       
  1095 }
       
  1096 
       
  1097 /**
       
  1098  * Builds an object with all post type capabilities out of a post type object
       
  1099  *
       
  1100  * Post type capabilities use the 'capability_type' argument as a base, if the
       
  1101  * capability is not set in the 'capabilities' argument array or if the
       
  1102  * 'capabilities' argument is not supplied.
       
  1103  *
       
  1104  * The capability_type argument can optionally be registered as an array, with
       
  1105  * the first value being singular and the second plural, e.g. array('story, 'stories')
       
  1106  * Otherwise, an 's' will be added to the value for the plural form. After
       
  1107  * registration, capability_type will always be a string of the singular value.
       
  1108  *
       
  1109  * By default, seven keys are accepted as part of the capabilities array:
       
  1110  *
       
  1111  * - edit_post, read_post, and delete_post are meta capabilities, which are then
       
  1112  *   generally mapped to corresponding primitive capabilities depending on the
       
  1113  *   context, which would be the post being edited/read/deleted and the user or
       
  1114  *   role being checked. Thus these capabilities would generally not be granted
       
  1115  *   directly to users or roles.
       
  1116  *
       
  1117  * - edit_posts - Controls whether objects of this post type can be edited.
       
  1118  * - edit_others_posts - Controls whether objects of this type owned by other users
       
  1119  *   can be edited. If the post type does not support an author, then this will
       
  1120  *   behave like edit_posts.
       
  1121  * - publish_posts - Controls publishing objects of this post type.
       
  1122  * - read_private_posts - Controls whether private objects can be read.
       
  1123  *
       
  1124  * These four primitive capabilities are checked in core in various locations.
       
  1125  * There are also seven other primitive capabilities which are not referenced
       
  1126  * directly in core, except in map_meta_cap(), which takes the three aforementioned
       
  1127  * meta capabilities and translates them into one or more primitive capabilities
       
  1128  * that must then be checked against the user or role, depending on the context.
       
  1129  *
       
  1130  * - read - Controls whether objects of this post type can be read.
       
  1131  * - delete_posts - Controls whether objects of this post type can be deleted.
       
  1132  * - delete_private_posts - Controls whether private objects can be deleted.
       
  1133  * - delete_published_posts - Controls whether published objects can be deleted.
       
  1134  * - delete_others_posts - Controls whether objects owned by other users can be
       
  1135  *   can be deleted. If the post type does not support an author, then this will
       
  1136  *   behave like delete_posts.
       
  1137  * - edit_private_posts - Controls whether private objects can be edited.
       
  1138  * - edit_published_posts - Controls whether published objects can be edited.
       
  1139  *
       
  1140  * These additional capabilities are only used in map_meta_cap(). Thus, they are
       
  1141  * only assigned by default if the post type is registered with the 'map_meta_cap'
       
  1142  * argument set to true (default is false).
       
  1143  *
       
  1144  * @see map_meta_cap()
       
  1145  * @since 3.0.0
       
  1146  *
       
  1147  * @param object $args Post type registration arguments
       
  1148  * @return object object with all the capabilities as member variables
       
  1149  */
       
  1150 function get_post_type_capabilities( $args ) {
       
  1151 	if ( ! is_array( $args->capability_type ) )
       
  1152 		$args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
       
  1153 
       
  1154 	// Singular base for meta capabilities, plural base for primitive capabilities.
       
  1155 	list( $singular_base, $plural_base ) = $args->capability_type;
       
  1156 
       
  1157 	$default_capabilities = array(
       
  1158 		// Meta capabilities
       
  1159 		'edit_post'          => 'edit_'         . $singular_base,
       
  1160 		'read_post'          => 'read_'         . $singular_base,
       
  1161 		'delete_post'        => 'delete_'       . $singular_base,
       
  1162 		// Primitive capabilities used outside of map_meta_cap():
       
  1163 		'edit_posts'         => 'edit_'         . $plural_base,
       
  1164 		'edit_others_posts'  => 'edit_others_'  . $plural_base,
       
  1165 		'publish_posts'      => 'publish_'      . $plural_base,
       
  1166 		'read_private_posts' => 'read_private_' . $plural_base,
       
  1167 	);
       
  1168 
       
  1169 	// Primitive capabilities used within map_meta_cap():
       
  1170 	if ( $args->map_meta_cap ) {
       
  1171 		$default_capabilities_for_mapping = array(
       
  1172 			'read'                   => 'read',
       
  1173 			'delete_posts'           => 'delete_'           . $plural_base,
       
  1174 			'delete_private_posts'   => 'delete_private_'   . $plural_base,
       
  1175 			'delete_published_posts' => 'delete_published_' . $plural_base,
       
  1176 			'delete_others_posts'    => 'delete_others_'    . $plural_base,
       
  1177 			'edit_private_posts'     => 'edit_private_'     . $plural_base,
       
  1178 			'edit_published_posts'   => 'edit_published_'   . $plural_base,
       
  1179 		);
       
  1180 		$default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
       
  1181 	}
       
  1182 
       
  1183 	$capabilities = array_merge( $default_capabilities, $args->capabilities );
       
  1184 
       
  1185 	// Remember meta capabilities for future reference.
       
  1186 	if ( $args->map_meta_cap )
       
  1187 		_post_type_meta_capabilities( $capabilities );
       
  1188 
       
  1189 	return (object) $capabilities;
       
  1190 }
       
  1191 
       
  1192 /**
       
  1193  * Stores or returns a list of post type meta caps for map_meta_cap().
       
  1194  *
       
  1195  * @since 3.1.0
       
  1196  * @access private
       
  1197  */
       
  1198 function _post_type_meta_capabilities( $capabilities = null ) {
       
  1199 	static $meta_caps = array();
       
  1200 	if ( null === $capabilities )
       
  1201 		return $meta_caps;
       
  1202 	foreach ( $capabilities as $core => $custom ) {
       
  1203 		if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
       
  1204 			$meta_caps[ $custom ] = $core;
       
  1205 	}
       
  1206 }
       
  1207 
       
  1208 /**
       
  1209  * Builds an object with all post type labels out of a post type object
       
  1210  *
       
  1211  * Accepted keys of the label array in the post type object:
       
  1212  * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
       
  1213  * - singular_name - name for one object of this post type. Default is Post/Page
       
  1214  * - 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>
       
  1215  * - add_new_item - Default is Add New Post/Add New Page
       
  1216  * - edit_item - Default is Edit Post/Edit Page
       
  1217  * - new_item - Default is New Post/New Page
       
  1218  * - view_item - Default is View Post/View Page
       
  1219  * - search_items - Default is Search Posts/Search Pages
       
  1220  * - not_found - Default is No posts found/No pages found
       
  1221  * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
       
  1222  * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
       
  1223  * - all_items - String for the submenu. Default is All Posts/All Pages
       
  1224  * - menu_name - Default is the same as <code>name</code>
       
  1225  *
       
  1226  * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
       
  1227  *
       
  1228  * @since 3.0.0
       
  1229  * @param object $post_type_object
       
  1230  * @return object object with all the labels as member variables
       
  1231  */
       
  1232 function get_post_type_labels( $post_type_object ) {
       
  1233 	$nohier_vs_hier_defaults = array(
       
  1234 		'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
       
  1235 		'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
       
  1236 		'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
       
  1237 		'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
       
  1238 		'edit_item' => array( __('Edit Post'), __('Edit Page') ),
       
  1239 		'new_item' => array( __('New Post'), __('New Page') ),
       
  1240 		'view_item' => array( __('View Post'), __('View Page') ),
       
  1241 		'search_items' => array( __('Search Posts'), __('Search Pages') ),
       
  1242 		'not_found' => array( __('No posts found.'), __('No pages found.') ),
       
  1243 		'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
       
  1244 		'parent_item_colon' => array( null, __('Parent Page:') ),
       
  1245 		'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
       
  1246 	);
       
  1247 	$nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
       
  1248 	return _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
       
  1249 }
       
  1250 
       
  1251 /**
       
  1252  * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
       
  1253  *
       
  1254  * @access private
       
  1255  * @since 3.0.0
       
  1256  */
       
  1257 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
       
  1258 
       
  1259 	if ( isset( $object->label ) && empty( $object->labels['name'] ) )
       
  1260 		$object->labels['name'] = $object->label;
       
  1261 
       
  1262 	if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
       
  1263 		$object->labels['singular_name'] = $object->labels['name'];
       
  1264 
       
  1265 	if ( ! isset( $object->labels['name_admin_bar'] ) )
       
  1266 		$object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
       
  1267 
       
  1268 	if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
       
  1269 		$object->labels['menu_name'] = $object->labels['name'];
       
  1270 
       
  1271 	if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
       
  1272 		$object->labels['all_items'] = $object->labels['menu_name'];
       
  1273 
       
  1274 	foreach ( $nohier_vs_hier_defaults as $key => $value )
       
  1275 			$defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
       
  1276 
       
  1277 	$labels = array_merge( $defaults, $object->labels );
       
  1278 	return (object)$labels;
       
  1279 }
       
  1280 
       
  1281 /**
       
  1282  * Adds submenus for post types.
       
  1283  *
       
  1284  * @access private
       
  1285  * @since 3.1.0
       
  1286  */
       
  1287 function _add_post_type_submenus() {
       
  1288 	foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
       
  1289 		$ptype_obj = get_post_type_object( $ptype );
       
  1290 		// Submenus only.
       
  1291 		if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
       
  1292 			continue;
       
  1293 		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" );
       
  1294 	}
       
  1295 }
       
  1296 add_action( 'admin_menu', '_add_post_type_submenus' );
       
  1297 
       
  1298 /**
       
  1299  * Register support of certain features for a post type.
       
  1300  *
       
  1301  * All features are directly associated with a functional area of the edit screen, such as the
       
  1302  * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
       
  1303  * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
       
  1304  *
       
  1305  * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
       
  1306  * and the 'comments' feature dictates whether the comments count will show on the edit screen.
       
  1307  *
       
  1308  * @since 3.0.0
       
  1309  * @param string $post_type The post type for which to add the feature
       
  1310  * @param string|array $feature the feature being added, can be an array of feature strings or a single string
       
  1311  */
       
  1312 function add_post_type_support( $post_type, $feature ) {
       
  1313 	global $_wp_post_type_features;
       
  1314 
       
  1315 	$features = (array) $feature;
       
  1316 	foreach ($features as $feature) {
       
  1317 		if ( func_num_args() == 2 )
       
  1318 			$_wp_post_type_features[$post_type][$feature] = true;
       
  1319 		else
       
  1320 			$_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
       
  1321 	}
       
  1322 }
       
  1323 
       
  1324 /**
       
  1325  * Remove support for a feature from a post type.
       
  1326  *
       
  1327  * @since 3.0.0
       
  1328  * @param string $post_type The post type for which to remove the feature
       
  1329  * @param string $feature The feature being removed
       
  1330  */
       
  1331 function remove_post_type_support( $post_type, $feature ) {
       
  1332 	global $_wp_post_type_features;
       
  1333 
       
  1334 	if ( !isset($_wp_post_type_features[$post_type]) )
       
  1335 		return;
       
  1336 
       
  1337 	if ( isset($_wp_post_type_features[$post_type][$feature]) )
       
  1338 		unset($_wp_post_type_features[$post_type][$feature]);
       
  1339 }
       
  1340 
       
  1341 /**
       
  1342  * Get all the post type features
       
  1343  *
       
  1344  * @since 3.4.0
       
  1345  * @param string $post_type The post type
       
  1346  * @return array
       
  1347  */
       
  1348 
       
  1349 function get_all_post_type_supports( $post_type ) {
       
  1350 	global $_wp_post_type_features;
       
  1351 
       
  1352 	if ( isset( $_wp_post_type_features[$post_type] ) )
       
  1353 		return $_wp_post_type_features[$post_type];
       
  1354 
       
  1355 	return array();
       
  1356 }
       
  1357 
       
  1358 /**
       
  1359  * Checks a post type's support for a given feature
       
  1360  *
       
  1361  * @since 3.0.0
       
  1362  * @param string $post_type The post type being checked
       
  1363  * @param string $feature the feature being checked
       
  1364  * @return boolean
       
  1365  */
       
  1366 
       
  1367 function post_type_supports( $post_type, $feature ) {
       
  1368 	global $_wp_post_type_features;
       
  1369 
       
  1370 	if ( !isset( $_wp_post_type_features[$post_type][$feature] ) )
       
  1371 		return false;
       
  1372 
       
  1373 	// If no args passed then no extra checks need be performed
       
  1374 	if ( func_num_args() <= 2 )
       
  1375 		return true;
       
  1376 
       
  1377 	// @todo Allow pluggable arg checking
       
  1378 	//$args = array_slice( func_get_args(), 2 );
       
  1379 
       
  1380 	return true;
   516 }
  1381 }
   517 
  1382 
   518 /**
  1383 /**
   519  * Updates the post type for the post ID.
  1384  * Updates the post type for the post ID.
   520  *
  1385  *
   531  */
  1396  */
   532 function set_post_type( $post_id = 0, $post_type = 'post' ) {
  1397 function set_post_type( $post_id = 0, $post_type = 'post' ) {
   533 	global $wpdb;
  1398 	global $wpdb;
   534 
  1399 
   535 	$post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
  1400 	$post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
   536 	$return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
  1401 	$return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
   537 
  1402 
   538 	if ( 'page' == $post_type )
  1403 	clean_post_cache( $post_id );
   539 		clean_page_cache($post_id);
       
   540 	else
       
   541 		clean_post_cache($post_id);
       
   542 
  1404 
   543 	return $return;
  1405 	return $return;
   544 }
  1406 }
   545 
  1407 
   546 /**
  1408 /**
   556  *     'exclude' - See {@link WP_Query::query()} for more.
  1418  *     'exclude' - See {@link WP_Query::query()} for more.
   557  *     'meta_key' - See {@link WP_Query::query()} for more.
  1419  *     'meta_key' - See {@link WP_Query::query()} for more.
   558  *     'meta_value' - See {@link WP_Query::query()} for more.
  1420  *     'meta_value' - See {@link WP_Query::query()} for more.
   559  *     'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
  1421  *     'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
   560  *     'post_parent' - The parent of the post or post type.
  1422  *     'post_parent' - The parent of the post or post type.
   561  *     'post_status' - Default is 'published'. Post status to retrieve.
  1423  *     'post_status' - Default is 'publish'. Post status to retrieve.
   562  *
  1424  *
   563  * @since 1.2.0
  1425  * @since 1.2.0
   564  * @uses $wpdb
  1426  * @uses $wpdb
   565  * @uses WP_Query::query() See for more default arguments and information.
  1427  * @uses WP_Query::query() See for more default arguments and information.
   566  * @link http://codex.wordpress.org/Template_Tags/get_posts
  1428  * @link http://codex.wordpress.org/Template_Tags/get_posts
   570  */
  1432  */
   571 function get_posts($args = null) {
  1433 function get_posts($args = null) {
   572 	$defaults = array(
  1434 	$defaults = array(
   573 		'numberposts' => 5, 'offset' => 0,
  1435 		'numberposts' => 5, 'offset' => 0,
   574 		'category' => 0, 'orderby' => 'post_date',
  1436 		'category' => 0, 'orderby' => 'post_date',
   575 		'order' => 'DESC', 'include' => '',
  1437 		'order' => 'DESC', 'include' => array(),
   576 		'exclude' => '', 'meta_key' => '',
  1438 		'exclude' => array(), 'meta_key' => '',
   577 		'meta_value' =>'', 'post_type' => 'post',
  1439 		'meta_value' =>'', 'post_type' => 'post',
   578 		'suppress_filters' => true
  1440 		'suppress_filters' => true
   579 	);
  1441 	);
   580 
  1442 
   581 	$r = wp_parse_args( $args, $defaults );
  1443 	$r = wp_parse_args( $args, $defaults );
   582 	if ( empty( $r['post_status'] ) )
  1444 	if ( empty( $r['post_status'] ) )
   583 		$r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
  1445 		$r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
   584 	if ( ! empty($r['numberposts']) )
  1446 	if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
   585 		$r['posts_per_page'] = $r['numberposts'];
  1447 		$r['posts_per_page'] = $r['numberposts'];
   586 	if ( ! empty($r['category']) )
  1448 	if ( ! empty($r['category']) )
   587 		$r['cat'] = $r['category'];
  1449 		$r['cat'] = $r['category'];
   588 	if ( ! empty($r['include']) ) {
  1450 	if ( ! empty($r['include']) ) {
   589 		$incposts = preg_split('/[\s,]+/',$r['include']);
  1451 		$incposts = wp_parse_id_list( $r['include'] );
   590 		$r['posts_per_page'] = count($incposts);  // only the number of posts included
  1452 		$r['posts_per_page'] = count($incposts);  // only the number of posts included
   591 		$r['post__in'] = $incposts;
  1453 		$r['post__in'] = $incposts;
   592 	} elseif ( ! empty($r['exclude']) )
  1454 	} elseif ( ! empty($r['exclude']) )
   593 		$r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
  1455 		$r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
   594 
  1456 
   595 	$r['caller_get_posts'] = true;
  1457 	$r['ignore_sticky_posts'] = true;
       
  1458 	$r['no_found_rows'] = true;
   596 
  1459 
   597 	$get_posts = new WP_Query;
  1460 	$get_posts = new WP_Query;
   598 	return $get_posts->query($r);
  1461 	return $get_posts->query($r);
   599 
  1462 
   600 }
  1463 }
   604 //
  1467 //
   605 
  1468 
   606 /**
  1469 /**
   607  * Add meta data field to a post.
  1470  * Add meta data field to a post.
   608  *
  1471  *
   609  * Post meta data is called "Custom Fields" on the Administration Panels.
  1472  * Post meta data is called "Custom Fields" on the Administration Screen.
   610  *
  1473  *
   611  * @since 1.5.0
  1474  * @since 1.5.0
   612  * @uses $wpdb
  1475  * @uses $wpdb
   613  * @link http://codex.wordpress.org/Function_Reference/add_post_meta
  1476  * @link http://codex.wordpress.org/Function_Reference/add_post_meta
   614  *
  1477  *
   615  * @param int $post_id Post ID.
  1478  * @param int $post_id Post ID.
   616  * @param string $key Metadata name.
  1479  * @param string $meta_key Metadata name.
   617  * @param mixed $value Metadata value.
  1480  * @param mixed $meta_value Metadata value.
   618  * @param bool $unique Optional, default is false. Whether the same key should not be added.
  1481  * @param bool $unique Optional, default is false. Whether the same key should not be added.
   619  * @return bool False for failure. True for success.
  1482  * @return bool False for failure. True for success.
   620  */
  1483  */
   621 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
  1484 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
   622 	// make sure meta is added to the post, not a revision
  1485 	// make sure meta is added to the post, not a revision
   656  * @since 1.5.0
  1519  * @since 1.5.0
   657  * @uses $wpdb
  1520  * @uses $wpdb
   658  * @link http://codex.wordpress.org/Function_Reference/get_post_meta
  1521  * @link http://codex.wordpress.org/Function_Reference/get_post_meta
   659  *
  1522  *
   660  * @param int $post_id Post ID.
  1523  * @param int $post_id Post ID.
   661  * @param string $key The meta key to retrieve.
  1524  * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
   662  * @param bool $single Whether to return a single value.
  1525  * @param bool $single Whether to return a single value.
   663  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  1526  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
   664  *  is true.
  1527  *  is true.
   665  */
  1528  */
   666 function get_post_meta($post_id, $key, $single = false) {
  1529 function get_post_meta($post_id, $key = '', $single = false) {
   667 	return get_metadata('post', $post_id, $key, $single);
  1530 	return get_metadata('post', $post_id, $key, $single);
   668 }
  1531 }
   669 
  1532 
   670 /**
  1533 /**
   671  * Update post meta field based on post ID.
  1534  * Update post meta field based on post ID.
   673  * Use the $prev_value parameter to differentiate between meta fields with the
  1536  * Use the $prev_value parameter to differentiate between meta fields with the
   674  * same key and post ID.
  1537  * same key and post ID.
   675  *
  1538  *
   676  * If the meta field for the post does not exist, it will be added.
  1539  * If the meta field for the post does not exist, it will be added.
   677  *
  1540  *
   678  * @since 1.5
  1541  * @since 1.5.0
   679  * @uses $wpdb
  1542  * @uses $wpdb
   680  * @link http://codex.wordpress.org/Function_Reference/update_post_meta
  1543  * @link http://codex.wordpress.org/Function_Reference/update_post_meta
   681  *
  1544  *
   682  * @param int $post_id Post ID.
  1545  * @param int $post_id Post ID.
   683  * @param string $key Metadata key.
  1546  * @param string $meta_key Metadata key.
   684  * @param mixed $value Metadata value.
  1547  * @param mixed $meta_value Metadata value.
   685  * @param mixed $prev_value Optional. Previous value to check before removing.
  1548  * @param mixed $prev_value Optional. Previous value to check before removing.
   686  * @return bool False on failure, true if success.
  1549  * @return bool False on failure, true if success.
   687  */
  1550  */
   688 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
  1551 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
   689 	// make sure meta is added to the post, not a revision
  1552 	// make sure meta is added to the post, not a revision
   701  *
  1564  *
   702  * @param string $post_meta_key Key to search for when deleting.
  1565  * @param string $post_meta_key Key to search for when deleting.
   703  * @return bool Whether the post meta key was deleted from the database
  1566  * @return bool Whether the post meta key was deleted from the database
   704  */
  1567  */
   705 function delete_post_meta_by_key($post_meta_key) {
  1568 function delete_post_meta_by_key($post_meta_key) {
   706 	if ( !$post_meta_key )
  1569 	return delete_metadata( 'post', null, $post_meta_key, '', true );
   707 		return false;
       
   708 
       
   709 	global $wpdb;
       
   710 	$post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
       
   711 	if ( $post_ids ) {
       
   712 		$postmetaids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key ) );
       
   713 		$in = implode( ',', array_fill(1, count($postmetaids), '%d'));
       
   714 		do_action( 'delete_postmeta', $postmetaids );
       
   715 		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN($in)", $postmetaids ));
       
   716 		do_action( 'deleted_postmeta', $postmetaids );
       
   717 		foreach ( $post_ids as $post_id )
       
   718 			wp_cache_delete($post_id, 'post_meta');
       
   719 		return true;
       
   720 	}
       
   721 	return false;
       
   722 }
  1570 }
   723 
  1571 
   724 /**
  1572 /**
   725  * Retrieve post meta fields, based on post ID.
  1573  * Retrieve post meta fields, based on post ID.
   726  *
  1574  *
   727  * The post meta fields are retrieved from the cache, so the function is
  1575  * The post meta fields are retrieved from the cache where possible,
   728  * optimized to be called more than once. It also applies to the functions, that
  1576  * so the function is optimized to be called more than once.
   729  * use this function.
       
   730  *
  1577  *
   731  * @since 1.2.0
  1578  * @since 1.2.0
   732  * @link http://codex.wordpress.org/Function_Reference/get_post_custom
  1579  * @link http://codex.wordpress.org/Function_Reference/get_post_custom
   733  *
  1580  *
   734  * @uses $id Current Loop Post ID
  1581  * @param int $post_id Post ID.
   735  *
       
   736  * @param int $post_id post ID
       
   737  * @return array
  1582  * @return array
   738  */
  1583  */
   739 function get_post_custom($post_id = 0) {
  1584 function get_post_custom( $post_id = 0 ) {
   740 	global $id;
  1585 	$post_id = absint( $post_id );
   741 
  1586 	if ( ! $post_id )
   742 	if ( !$post_id )
  1587 		$post_id = get_the_ID();
   743 		$post_id = (int) $id;
  1588 
   744 
  1589 	return get_post_meta( $post_id );
   745 	$post_id = (int) $post_id;
       
   746 
       
   747 	if ( ! wp_cache_get($post_id, 'post_meta') )
       
   748 		update_postmeta_cache($post_id);
       
   749 
       
   750 	return wp_cache_get($post_id, 'post_meta');
       
   751 }
  1590 }
   752 
  1591 
   753 /**
  1592 /**
   754  * Retrieve meta field names for a post.
  1593  * Retrieve meta field names for a post.
   755  *
  1594  *
   800  * given, then The Loop ID for the current post will be used.
  1639  * given, then The Loop ID for the current post will be used.
   801  *
  1640  *
   802  * @since 2.7.0
  1641  * @since 2.7.0
   803  *
  1642  *
   804  * @param int $post_id Optional. Post ID.
  1643  * @param int $post_id Optional. Post ID.
   805  * @return bool Whether post is sticky (true) or not sticky (false).
  1644  * @return bool Whether post is sticky.
   806  */
  1645  */
   807 function is_sticky($post_id = null) {
  1646 function is_sticky( $post_id = 0 ) {
   808 	global $id;
  1647 	$post_id = absint( $post_id );
   809 
  1648 
   810 	$post_id = absint($post_id);
  1649 	if ( ! $post_id )
   811 
  1650 		$post_id = get_the_ID();
   812 	if ( !$post_id )
  1651 
   813 		$post_id = absint($id);
  1652 	$stickies = get_option( 'sticky_posts' );
   814 
  1653 
   815 	$stickies = get_option('sticky_posts');
  1654 	if ( ! is_array( $stickies ) )
   816 
       
   817 	if ( !is_array($stickies) )
       
   818 		return false;
  1655 		return false;
   819 
  1656 
   820 	if ( in_array($post_id, $stickies) )
  1657 	if ( in_array( $post_id, $stickies ) )
   821 		return true;
  1658 		return true;
   822 
  1659 
   823 	return false;
  1660 	return false;
   824 }
  1661 }
   825 
  1662 
   853 			$post['ID'] = 0;
  1690 			$post['ID'] = 0;
   854 		foreach ( array_keys($post) as $field )
  1691 		foreach ( array_keys($post) as $field )
   855 			$post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
  1692 			$post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
   856 		$post['filter'] = $context;
  1693 		$post['filter'] = $context;
   857 	}
  1694 	}
   858 
       
   859 	return $post;
  1695 	return $post;
   860 }
  1696 }
   861 
  1697 
   862 /**
  1698 /**
   863  * Sanitize post field based on context.
  1699  * Sanitize post field based on context.
   865  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1701  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
   866  * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1702  * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
   867  * when calling filters.
  1703  * when calling filters.
   868  *
  1704  *
   869  * @since 2.3.0
  1705  * @since 2.3.0
   870  * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
  1706  * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
   871  *  $post_id if $context == 'edit' and field name prefix == 'post_'.
  1707  *  $post_id if $context == 'edit' and field name prefix == 'post_'.
   872  *
  1708  *
   873  * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
  1709  * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
   874  * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
  1710  * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
   875  * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
  1711  * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
   876  *
  1712  *
   877  * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
  1713  * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
   878  *  other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
  1714  *  other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
   879  * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
  1715  * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
   880  *  'edit' and 'db' and field name prefix != 'post_'.
  1716  *  'edit' and 'db' and field name prefix != 'post_'.
   889 function sanitize_post_field($field, $value, $post_id, $context) {
  1725 function sanitize_post_field($field, $value, $post_id, $context) {
   890 	$int_fields = array('ID', 'post_parent', 'menu_order');
  1726 	$int_fields = array('ID', 'post_parent', 'menu_order');
   891 	if ( in_array($field, $int_fields) )
  1727 	if ( in_array($field, $int_fields) )
   892 		$value = (int) $value;
  1728 		$value = (int) $value;
   893 
  1729 
       
  1730 	// Fields which contain arrays of ints.
       
  1731 	$array_int_fields = array( 'ancestors' );
       
  1732 	if ( in_array($field, $array_int_fields) ) {
       
  1733 		$value = array_map( 'absint', $value);
       
  1734 		return $value;
       
  1735 	}
       
  1736 
   894 	if ( 'raw' == $context )
  1737 	if ( 'raw' == $context )
   895 		return $value;
  1738 		return $value;
   896 
  1739 
   897 	$prefixed = false;
  1740 	$prefixed = false;
   898 	if ( false !== strpos($field, 'post_') ) {
  1741 	if ( false !== strpos($field, 'post_') ) {
   902 
  1745 
   903 	if ( 'edit' == $context ) {
  1746 	if ( 'edit' == $context ) {
   904 		$format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
  1747 		$format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
   905 
  1748 
   906 		if ( $prefixed ) {
  1749 		if ( $prefixed ) {
   907 			$value = apply_filters("edit_$field", $value, $post_id);
  1750 			$value = apply_filters("edit_{$field}", $value, $post_id);
   908 			// Old school
  1751 			// Old school
   909 			$value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
  1752 			$value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
   910 		} else {
  1753 		} else {
   911 			$value = apply_filters("edit_post_$field", $value, $post_id);
  1754 			$value = apply_filters("edit_post_{$field}", $value, $post_id);
   912 		}
  1755 		}
   913 
  1756 
   914 		if ( in_array($field, $format_to_edit) ) {
  1757 		if ( in_array($field, $format_to_edit) ) {
   915 			if ( 'post_content' == $field )
  1758 			if ( 'post_content' == $field )
   916 				$value = format_to_edit($value, user_can_richedit());
  1759 				$value = format_to_edit($value, user_can_richedit());
   919 		} else {
  1762 		} else {
   920 			$value = esc_attr($value);
  1763 			$value = esc_attr($value);
   921 		}
  1764 		}
   922 	} else if ( 'db' == $context ) {
  1765 	} else if ( 'db' == $context ) {
   923 		if ( $prefixed ) {
  1766 		if ( $prefixed ) {
   924 			$value = apply_filters("pre_$field", $value);
  1767 			$value = apply_filters("pre_{$field}", $value);
   925 			$value = apply_filters("${field_no_prefix}_save_pre", $value);
  1768 			$value = apply_filters("{$field_no_prefix}_save_pre", $value);
   926 		} else {
  1769 		} else {
   927 			$value = apply_filters("pre_post_$field", $value);
  1770 			$value = apply_filters("pre_post_{$field}", $value);
   928 			$value = apply_filters("${field}_pre", $value);
  1771 			$value = apply_filters("{$field}_pre", $value);
   929 		}
  1772 		}
   930 	} else {
  1773 	} else {
   931 		// Use display filters by default.
  1774 		// Use display filters by default.
   932 		if ( $prefixed )
  1775 		if ( $prefixed )
   933 			$value = apply_filters($field, $value, $post_id, $context);
  1776 			$value = apply_filters($field, $value, $post_id, $context);
   934 		else
  1777 		else
   935 			$value = apply_filters("post_$field", $value, $post_id, $context);
  1778 			$value = apply_filters("post_{$field}", $value, $post_id, $context);
   936 	}
  1779 	}
   937 
  1780 
   938 	if ( 'attribute' == $context )
  1781 	if ( 'attribute' == $context )
   939 		$value = esc_attr($value);
  1782 		$value = esc_attr($value);
   940 	else if ( 'js' == $context )
  1783 	else if ( 'js' == $context )
  1016 
  1859 
  1017 	$cache_key = $type;
  1860 	$cache_key = $type;
  1018 
  1861 
  1019 	$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
  1862 	$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
  1020 	if ( 'readable' == $perm && is_user_logged_in() ) {
  1863 	if ( 'readable' == $perm && is_user_logged_in() ) {
  1021 		if ( !current_user_can("read_private_{$type}s") ) {
  1864 		$post_type_object = get_post_type_object($type);
       
  1865 		if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
  1022 			$cache_key .= '_' . $perm . '_' . $user->ID;
  1866 			$cache_key .= '_' . $perm . '_' . $user->ID;
  1023 			$query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
  1867 			$query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
  1024 		}
  1868 		}
  1025 	}
  1869 	}
  1026 	$query .= ' GROUP BY post_status';
  1870 	$query .= ' GROUP BY post_status';
  1029 	if ( false !== $count )
  1873 	if ( false !== $count )
  1030 		return $count;
  1874 		return $count;
  1031 
  1875 
  1032 	$count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
  1876 	$count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
  1033 
  1877 
  1034 	$stats = array( 'publish' => 0, 'private' => 0, 'draft' => 0, 'pending' => 0, 'future' => 0, 'trash' => 0 );
  1878 	$stats = array();
  1035 	foreach( (array) $count as $row_num => $row ) {
  1879 	foreach ( get_post_stati() as $state )
       
  1880 		$stats[$state] = 0;
       
  1881 
       
  1882 	foreach ( (array) $count as $row )
  1036 		$stats[$row['post_status']] = $row['num_posts'];
  1883 		$stats[$row['post_status']] = $row['num_posts'];
  1037 	}
       
  1038 
  1884 
  1039 	$stats = (object) $stats;
  1885 	$stats = (object) $stats;
  1040 	wp_cache_set($cache_key, $stats, 'counts');
  1886 	wp_cache_set($cache_key, $stats, 'counts');
  1041 
  1887 
  1042 	return $stats;
  1888 	return $stats;
  1043 }
  1889 }
  1044 
       
  1045 
  1890 
  1046 /**
  1891 /**
  1047  * Count number of attachments for the mime type(s).
  1892  * Count number of attachments for the mime type(s).
  1048  *
  1893  *
  1049  * If you set the optional mime_type parameter, then an array will still be
  1894  * If you set the optional mime_type parameter, then an array will still be
  1112 /**
  1957 /**
  1113  * Convert MIME types into SQL.
  1958  * Convert MIME types into SQL.
  1114  *
  1959  *
  1115  * @since 2.5.0
  1960  * @since 2.5.0
  1116  *
  1961  *
  1117  * @param string|array $mime_types List of mime types or comma separated string of mime types.
  1962  * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
       
  1963  * @param string $table_alias Optional. Specify a table alias, if needed.
  1118  * @return string The SQL AND clause for mime searching.
  1964  * @return string The SQL AND clause for mime searching.
  1119  */
  1965  */
  1120 function wp_post_mime_type_where($post_mime_types) {
  1966 function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
  1121 	$where = '';
  1967 	$where = '';
  1122 	$wildcards = array('', '%', '%/%');
  1968 	$wildcards = array('', '%', '%/%');
  1123 	if ( is_string($post_mime_types) )
  1969 	if ( is_string($post_mime_types) )
  1124 		$post_mime_types = array_map('trim', explode(',', $post_mime_types));
  1970 		$post_mime_types = array_map('trim', explode(',', $post_mime_types));
  1125 	foreach ( (array) $post_mime_types as $mime_type ) {
  1971 	foreach ( (array) $post_mime_types as $mime_type ) {
  1143 
  1989 
  1144 		if ( in_array( $mime_type, $wildcards ) )
  1990 		if ( in_array( $mime_type, $wildcards ) )
  1145 			return '';
  1991 			return '';
  1146 
  1992 
  1147 		if ( false !== strpos($mime_pattern, '%') )
  1993 		if ( false !== strpos($mime_pattern, '%') )
  1148 			$wheres[] = "post_mime_type LIKE '$mime_pattern'";
  1994 			$wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
  1149 		else
  1995 		else
  1150 			$wheres[] = "post_mime_type = '$mime_pattern'";
  1996 			$wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
  1151 	}
  1997 	}
  1152 	if ( !empty($wheres) )
  1998 	if ( !empty($wheres) )
  1153 		$where = ' AND (' . join(' OR ', $wheres) . ') ';
  1999 		$where = ' AND (' . join(' OR ', $wheres) . ') ';
  1154 	return $where;
  2000 	return $where;
  1155 }
  2001 }
  1156 
  2002 
  1157 /**
  2003 /**
  1158  * Removes a post, attachment, or page.
  2004  * Trashes or deletes a post or page.
  1159  *
  2005  *
  1160  * When the post and page goes, everything that is tied to it is deleted also.
  2006  * When the post and page is permanently deleted, everything that is tied to it is deleted also.
  1161  * This includes comments, post meta fields, and terms associated with the post.
  2007  * This includes comments, post meta fields, and terms associated with the post.
       
  2008  *
       
  2009  * The post or page is moved to trash instead of permanently deleted unless trash is
       
  2010  * disabled, item is already in the trash, or $force_delete is true.
  1162  *
  2011  *
  1163  * @since 1.0.0
  2012  * @since 1.0.0
  1164  * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
  2013  * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
  1165  * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
  2014  * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
  1166  * @uses wp_delete_attachment() if post type is 'attachment'.
  2015  * @uses wp_delete_attachment() if post type is 'attachment'.
       
  2016  * @uses wp_trash_post() if item should be trashed.
  1167  *
  2017  *
  1168  * @param int $postid Post ID.
  2018  * @param int $postid Post ID.
  1169  * @param bool $force_delete Whether to bypass trash and force deletion
  2019  * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  1170  * @return mixed False on failure
  2020  * @return mixed False on failure
  1171  */
  2021  */
  1172 function wp_delete_post( $postid = 0, $force_delete = false ) {
  2022 function wp_delete_post( $postid = 0, $force_delete = false ) {
  1173 	global $wpdb, $wp_rewrite;
  2023 	global $wpdb;
  1174 
  2024 
  1175 	if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
  2025 	if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
  1176 		return $post;
  2026 		return $post;
  1177 
  2027 
  1178 	if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS > 0 )
  2028 	if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
  1179 			return wp_trash_post($postid);
  2029 			return wp_trash_post($postid);
  1180 
  2030 
  1181 	if ( $post->post_type == 'attachment' )
  2031 	if ( $post->post_type == 'attachment' )
  1182 		return wp_delete_attachment( $postid, $force_delete );
  2032 		return wp_delete_attachment( $postid, $force_delete );
  1183 
  2033 
  1184 	do_action('delete_post', $postid);
  2034 	do_action('before_delete_post', $postid);
  1185 
  2035 
  1186 	delete_post_meta($postid,'_wp_trash_meta_status');
  2036 	delete_post_meta($postid,'_wp_trash_meta_status');
  1187 	delete_post_meta($postid,'_wp_trash_meta_time');
  2037 	delete_post_meta($postid,'_wp_trash_meta_time');
  1188 
  2038 
  1189 	wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
  2039 	wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
  1190 
  2040 
  1191 	$parent_data = array( 'post_parent' => $post->post_parent );
  2041 	$parent_data = array( 'post_parent' => $post->post_parent );
  1192 	$parent_where = array( 'post_parent' => $postid );
  2042 	$parent_where = array( 'post_parent' => $postid );
       
  2043 
       
  2044 	if ( is_post_type_hierarchical( $post->post_type ) ) {
       
  2045 		// Point children of this page to its parent, also clean the cache of affected children
       
  2046 		$children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
       
  2047 		$children = $wpdb->get_results( $children_query );
       
  2048 
       
  2049 		$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
       
  2050 	}
  1193 
  2051 
  1194 	if ( 'page' == $post->post_type) {
  2052 	if ( 'page' == $post->post_type) {
  1195 	 	// if the page is defined in option page_on_front or post_for_posts,
  2053 	 	// if the page is defined in option page_on_front or post_for_posts,
  1196 		// adjust the corresponding options
  2054 		// adjust the corresponding options
  1197 		if ( get_option('page_on_front') == $postid ) {
  2055 		if ( get_option('page_on_front') == $postid ) {
  1199 			delete_option('page_on_front');
  2057 			delete_option('page_on_front');
  1200 		}
  2058 		}
  1201 		if ( get_option('page_for_posts') == $postid ) {
  2059 		if ( get_option('page_for_posts') == $postid ) {
  1202 			delete_option('page_for_posts');
  2060 			delete_option('page_for_posts');
  1203 		}
  2061 		}
  1204 
       
  1205 		// Point children of this page to its parent, also clean the cache of affected children
       
  1206 		$children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
       
  1207 		$children = $wpdb->get_results($children_query);
       
  1208 
       
  1209 		$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
       
  1210 	} else {
  2062 	} else {
  1211 		unstick_post($postid);
  2063 		unstick_post($postid);
  1212 	}
  2064 	}
  1213 
  2065 
  1214 	// Do raw query.  wp_get_post_revisions() is filtered
  2066 	// Do raw query. wp_get_post_revisions() is filtered
  1215 	$revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
  2067 	$revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
  1216 	// Use wp_delete_post (via wp_delete_post_revision) again.  Ensures any meta/misplaced data gets cleaned up.
  2068 	// Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
  1217 	foreach ( $revision_ids as $revision_id )
  2069 	foreach ( $revision_ids as $revision_id )
  1218 		wp_delete_post_revision( $revision_id );
  2070 		wp_delete_post_revision( $revision_id );
  1219 
  2071 
  1220 	// Point all attachments to this post up one level
  2072 	// Point all attachments to this post up one level
  1221 	$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
  2073 	$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
  1222 
  2074 
  1223 	$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
  2075 	$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
  1224 	if ( ! empty($comment_ids) ) {
  2076 	foreach ( $comment_ids as $comment_id )
  1225 		do_action( 'delete_comment', $comment_ids );
  2077 		wp_delete_comment( $comment_id, true );
  1226 		$in_comment_ids = "'" . implode("', '", $comment_ids) . "'";
       
  1227 		$wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_ID IN($in_comment_ids)" );
       
  1228 		do_action( 'deleted_comment', $comment_ids );
       
  1229 	}
       
  1230 
  2078 
  1231 	$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
  2079 	$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
  1232 	if ( !empty($post_meta_ids) ) {
  2080 	foreach ( $post_meta_ids as $mid )
  1233 		do_action( 'delete_postmeta', $post_meta_ids );
  2081 		delete_metadata_by_mid( 'post', $mid );
  1234 		$in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
       
  1235 		$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
       
  1236 		do_action( 'deleted_postmeta', $post_meta_ids );
       
  1237 	}
       
  1238 
  2082 
  1239 	do_action( 'delete_post', $postid );
  2083 	do_action( 'delete_post', $postid );
  1240 	$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
  2084 	$wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
  1241 	do_action( 'deleted_post', $postid );
  2085 	do_action( 'deleted_post', $postid );
  1242 
  2086 
  1243 	if ( 'page' == $post->post_type ) {
  2087 	clean_post_cache( $post );
  1244 		clean_page_cache($postid);
  2088 
  1245 
  2089 	if ( is_post_type_hierarchical( $post->post_type ) ) {
  1246 		foreach ( (array) $children as $child )
  2090 		foreach ( (array) $children as $child )
  1247 			clean_page_cache($child->ID);
  2091 			clean_post_cache( $child );
  1248 
  2092 	}
  1249 		$wp_rewrite->flush_rules(false);
  2093 
  1250 	} else {
  2094 	wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
  1251 		clean_post_cache($postid);
  2095 
  1252 	}
  2096 	do_action('after_delete_post', $postid);
  1253 
       
  1254 	wp_clear_scheduled_hook('publish_future_post', $postid);
       
  1255 
       
  1256 	do_action('deleted_post', $postid);
       
  1257 
  2097 
  1258 	return $post;
  2098 	return $post;
  1259 }
  2099 }
  1260 
  2100 
  1261 /**
  2101 /**
  1262  * Moves a post or page to the Trash
  2102  * Moves a post or page to the Trash
       
  2103  *
       
  2104  * If trash is disabled, the post or page is permanently deleted.
  1263  *
  2105  *
  1264  * @since 2.9.0
  2106  * @since 2.9.0
  1265  * @uses do_action() on 'trash_post' before trashing
  2107  * @uses do_action() on 'trash_post' before trashing
  1266  * @uses do_action() on 'trashed_post' after trashing
  2108  * @uses do_action() on 'trashed_post' after trashing
  1267  *
  2109  * @uses wp_delete_post() if trash is disabled
  1268  * @param int $postid Post ID.
  2110  *
       
  2111  * @param int $post_id Post ID.
  1269  * @return mixed False on failure
  2112  * @return mixed False on failure
  1270  */
  2113  */
  1271 function wp_trash_post($post_id = 0) {
  2114 function wp_trash_post($post_id = 0) {
  1272 	if ( EMPTY_TRASH_DAYS == 0 )
  2115 	if ( !EMPTY_TRASH_DAYS )
  1273 		return wp_delete_post($post_id);
  2116 		return wp_delete_post($post_id, true);
  1274 
  2117 
  1275 	if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  2118 	if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1276 		return $post;
  2119 		return $post;
  1277 
  2120 
  1278 	if ( $post['post_status'] == 'trash' )
  2121 	if ( $post['post_status'] == 'trash' )
  1279 		return false;
  2122 		return false;
  1280 
  2123 
  1281 	do_action('trash_post', $post_id);
  2124 	do_action('wp_trash_post', $post_id);
  1282 
  2125 
  1283 	add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
  2126 	add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
  1284 	add_post_meta($post_id,'_wp_trash_meta_time', time());
  2127 	add_post_meta($post_id,'_wp_trash_meta_time', time());
  1285 
  2128 
  1286 	$post['post_status'] = 'trash';
  2129 	$post['post_status'] = 'trash';
  1298  *
  2141  *
  1299  * @since 2.9.0
  2142  * @since 2.9.0
  1300  * @uses do_action() on 'untrash_post' before undeletion
  2143  * @uses do_action() on 'untrash_post' before undeletion
  1301  * @uses do_action() on 'untrashed_post' after undeletion
  2144  * @uses do_action() on 'untrashed_post' after undeletion
  1302  *
  2145  *
  1303  * @param int $postid Post ID.
  2146  * @param int $post_id Post ID.
  1304  * @return mixed False on failure
  2147  * @return mixed False on failure
  1305  */
  2148  */
  1306 function wp_untrash_post($post_id = 0) {
  2149 function wp_untrash_post($post_id = 0) {
  1307 	if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  2150 	if ( !$post = wp_get_single_post($post_id, ARRAY_A) )
  1308 		return $post;
  2151 		return $post;
  1491 
  2334 
  1492 /**
  2335 /**
  1493  * Retrieve number of recent posts.
  2336  * Retrieve number of recent posts.
  1494  *
  2337  *
  1495  * @since 1.0.0
  2338  * @since 1.0.0
  1496  * @uses $wpdb
  2339  * @uses wp_parse_args()
  1497  *
  2340  * @uses get_posts()
  1498  * @param int $num Optional, default is 10. Number of posts to get.
  2341  *
  1499  * @return array List of posts.
  2342  * @param string $deprecated Deprecated.
  1500  */
  2343  * @param array $args Optional. Overrides defaults.
  1501 function wp_get_recent_posts($num = 10) {
  2344  * @param string $output Optional.
  1502 	global $wpdb;
  2345  * @return unknown.
  1503 
  2346  */
  1504 	// Set the limit clause, if we got a limit
  2347 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
  1505 	$num = (int) $num;
  2348 
  1506 	if ( $num ) {
  2349 	if ( is_numeric( $args ) ) {
  1507 		$limit = "LIMIT $num";
  2350 		_deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  1508 	}
  2351 		$args = array( 'numberposts' => absint( $args ) );
  1509 
  2352 	}
  1510 	$sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status IN ( 'draft', 'publish', 'future', 'pending', 'private' ) ORDER BY post_date DESC $limit";
  2353 
  1511 	$result = $wpdb->get_results($sql, ARRAY_A);
  2354 	// Set default arguments
  1512 
  2355 	$defaults = array(
  1513 	return $result ? $result : array();
  2356 		'numberposts' => 10, 'offset' => 0,
       
  2357 		'category' => 0, 'orderby' => 'post_date',
       
  2358 		'order' => 'DESC', 'include' => '',
       
  2359 		'exclude' => '', 'meta_key' => '',
       
  2360 		'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
       
  2361 		'suppress_filters' => true
       
  2362 	);
       
  2363 
       
  2364 	$r = wp_parse_args( $args, $defaults );
       
  2365 
       
  2366 	$results = get_posts( $r );
       
  2367 
       
  2368 	// Backward compatibility. Prior to 3.1 expected posts to be returned in array
       
  2369 	if ( ARRAY_A == $output ){
       
  2370 		foreach( $results as $key => $result ) {
       
  2371 			$results[$key] = get_object_vars( $result );
       
  2372 		}
       
  2373 		return $results ? $results : array();
       
  2374 	}
       
  2375 
       
  2376 	return $results ? $results : false;
       
  2377 
  1514 }
  2378 }
  1515 
  2379 
  1516 /**
  2380 /**
  1517  * Retrieve a single post, based on post ID.
  2381  * Retrieve a single post, based on post ID.
  1518  *
  2382  *
  1528 function wp_get_single_post($postid = 0, $mode = OBJECT) {
  2392 function wp_get_single_post($postid = 0, $mode = OBJECT) {
  1529 	$postid = (int) $postid;
  2393 	$postid = (int) $postid;
  1530 
  2394 
  1531 	$post = get_post($postid, $mode);
  2395 	$post = get_post($postid, $mode);
  1532 
  2396 
       
  2397 	if (
       
  2398 		( OBJECT == $mode && empty( $post->ID ) ) ||
       
  2399 		( OBJECT != $mode && empty( $post['ID'] ) )
       
  2400 	)
       
  2401 		return ( OBJECT == $mode ? null : array() );
       
  2402 
  1533 	// Set categories and tags
  2403 	// Set categories and tags
  1534 	if($mode == OBJECT) {
  2404 	if ( $mode == OBJECT ) {
  1535 		$post->post_category = wp_get_post_categories($postid);
  2405 		$post->post_category = array();
  1536 		$post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
  2406 		if ( is_object_in_taxonomy($post->post_type, 'category') )
  1537 	}
  2407 			$post->post_category = wp_get_post_categories($postid);
  1538 	else {
  2408 		$post->tags_input = array();
  1539 		$post['post_category'] = wp_get_post_categories($postid);
  2409 		if ( is_object_in_taxonomy($post->post_type, 'post_tag') )
  1540 		$post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
  2410 			$post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
       
  2411 	} else {
       
  2412 		$post['post_category'] = array();
       
  2413 		if ( is_object_in_taxonomy($post['post_type'], 'category') )
       
  2414 			$post['post_category'] = wp_get_post_categories($postid);
       
  2415 		$post['tags_input'] = array();
       
  2416 		if ( is_object_in_taxonomy($post['post_type'], 'post_tag') )
       
  2417 			$post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
  1541 	}
  2418 	}
  1542 
  2419 
  1543 	return $post;
  2420 	return $post;
  1544 }
  2421 }
  1545 
  2422 
  1566  *     'guid'          - Global Unique ID for referencing the attachment.
  2443  *     'guid'          - Global Unique ID for referencing the attachment.
  1567  *     'post_content_filtered' - Post content filtered.
  2444  *     'post_content_filtered' - Post content filtered.
  1568  *     'post_excerpt'  - Post excerpt.
  2445  *     'post_excerpt'  - Post excerpt.
  1569  *
  2446  *
  1570  * @since 1.0.0
  2447  * @since 1.0.0
  1571  * @link http://core.trac.wordpress.org/ticket/9084 Bug report on 'wp_insert_post_data' filter.
       
  1572  * @uses $wpdb
  2448  * @uses $wpdb
  1573  * @uses $wp_rewrite
       
  1574  * @uses $user_ID
  2449  * @uses $user_ID
  1575  *
       
  1576  * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
  2450  * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
  1577  * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
  2451  * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
  1578  * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before
  2452  * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
  1579  *                   returning.
  2453  * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
  1580  *
       
  1581  * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database
       
  1582  *                       update or insert.
       
  1583  * @uses wp_transition_post_status()
  2454  * @uses wp_transition_post_status()
  1584  *
  2455  *
  1585  * @param array $postarr Optional. Overrides defaults.
  2456  * @param array $postarr Elements that make up post to insert.
  1586  * @param bool $wp_error Optional. Allow return of WP_Error on failure.
  2457  * @param bool $wp_error Optional. Allow return of WP_Error on failure.
  1587  * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  2458  * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  1588  */
  2459  */
  1589 function wp_insert_post($postarr = array(), $wp_error = false) {
  2460 function wp_insert_post($postarr, $wp_error = false) {
  1590 	global $wpdb, $wp_rewrite, $user_ID;
  2461 	global $wpdb, $user_ID;
  1591 
  2462 
  1592 	$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  2463 	$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  1593 		'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  2464 		'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  1594 		'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
  2465 		'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
  1595 		'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
  2466 		'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
       
  2467 		'post_content' => '', 'post_title' => '');
  1596 
  2468 
  1597 	$postarr = wp_parse_args($postarr, $defaults);
  2469 	$postarr = wp_parse_args($postarr, $defaults);
       
  2470 
       
  2471 	unset( $postarr[ 'filter' ] );
       
  2472 
  1598 	$postarr = sanitize_post($postarr, 'db');
  2473 	$postarr = sanitize_post($postarr, 'db');
  1599 
  2474 
  1600 	// export array as variables
  2475 	// export array as variables
  1601 	extract($postarr, EXTR_SKIP);
  2476 	extract($postarr, EXTR_SKIP);
  1602 
  2477 
  1607 		$previous_status = get_post_field('post_status', $ID);
  2482 		$previous_status = get_post_field('post_status', $ID);
  1608 	} else {
  2483 	} else {
  1609 		$previous_status = 'new';
  2484 		$previous_status = 'new';
  1610 	}
  2485 	}
  1611 
  2486 
  1612 	if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
  2487 	$maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' )
       
  2488 		&& post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' );
       
  2489 	if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
  1613 		if ( $wp_error )
  2490 		if ( $wp_error )
  1614 			return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
  2491 			return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
  1615 		else
  2492 		else
  1616 			return 0;
  2493 			return 0;
  1617 	}
  2494 	}
  1618 
  2495 
  1619 	// Make sure we set a valid category
  2496 	if ( empty($post_type) )
       
  2497 		$post_type = 'post';
       
  2498 
       
  2499 	if ( empty($post_status) )
       
  2500 		$post_status = 'draft';
       
  2501 
       
  2502 	if ( !empty($post_category) )
       
  2503 		$post_category = array_filter($post_category); // Filter out empty terms
       
  2504 
       
  2505 	// Make sure we set a valid category.
  1620 	if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  2506 	if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  1621 		$post_category = array(get_option('default_category'));
  2507 		// 'post' requires at least one category.
  1622 	}
  2508 		if ( 'post' == $post_type && 'auto-draft' != $post_status )
  1623 
  2509 			$post_category = array( get_option('default_category') );
  1624 	//Set the default tag list
  2510 		else
  1625 	if ( !isset($tags_input) )
  2511 			$post_category = array();
  1626 		$tags_input = array();
  2512 	}
  1627 
  2513 
  1628 	if ( empty($post_author) )
  2514 	if ( empty($post_author) )
  1629 		$post_author = $user_ID;
  2515 		$post_author = $user_ID;
  1630 
       
  1631 	if ( empty($post_status) )
       
  1632 		$post_status = 'draft';
       
  1633 
       
  1634 	if ( empty($post_type) )
       
  1635 		$post_type = 'post';
       
  1636 
  2516 
  1637 	$post_ID = 0;
  2517 	$post_ID = 0;
  1638 
  2518 
  1639 	// Get the post ID and GUID
  2519 	// Get the post ID and GUID
  1640 	if ( $update ) {
  2520 	if ( $update ) {
  1641 		$post_ID = (int) $ID;
  2521 		$post_ID = (int) $ID;
  1642 		$guid = get_post_field( 'guid', $post_ID );
  2522 		$guid = get_post_field( 'guid', $post_ID );
  1643 	}
  2523 		$post_before = get_post($post_ID);
  1644 
  2524 	}
  1645 	// Don't allow contributors to set to set the post slug for pending review posts
  2525 
       
  2526 	// Don't allow contributors to set the post slug for pending review posts
  1646 	if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
  2527 	if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
  1647 		$post_name = '';
  2528 		$post_name = '';
  1648 
  2529 
  1649 	// Create a valid post name.  Drafts and pending posts are allowed to have an empty
  2530 	// Create a valid post name. Drafts and pending posts are allowed to have an empty
  1650 	// post name.
  2531 	// post name.
  1651 	if ( !isset($post_name) || empty($post_name) ) {
  2532 	if ( empty($post_name) ) {
  1652 		if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
  2533 		if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  1653 			$post_name = sanitize_title($post_title);
  2534 			$post_name = sanitize_title($post_title);
  1654 		else
  2535 		else
  1655 			$post_name = '';
  2536 			$post_name = '';
  1656 	} else {
  2537 	} else {
  1657 		$post_name = sanitize_title($post_name);
  2538 		// On updates, we need to check to see if it's using the old, fixed sanitization context.
       
  2539 		$check_name = sanitize_title( $post_name, '', 'old-save' );
       
  2540 		if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name )
       
  2541 			$post_name = $check_name;
       
  2542 		else // new post, or slug has changed.
       
  2543 			$post_name = sanitize_title($post_name);
  1658 	}
  2544 	}
  1659 
  2545 
  1660 	// 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
  2546 	// 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
  1661 	if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
  2547 	if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
  1662 		$post_date = current_time('mysql');
  2548 		$post_date = current_time('mysql');
  1663 
  2549 
  1664 	if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
  2550 	if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
  1665 		if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
  2551 		if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  1666 			$post_date_gmt = get_gmt_from_date($post_date);
  2552 			$post_date_gmt = get_gmt_from_date($post_date);
  1667 		else
  2553 		else
  1668 			$post_date_gmt = '0000-00-00 00:00:00';
  2554 			$post_date_gmt = '0000-00-00 00:00:00';
  1669 	}
  2555 	}
  1670 
  2556 
  1678 
  2564 
  1679 	if ( 'publish' == $post_status ) {
  2565 	if ( 'publish' == $post_status ) {
  1680 		$now = gmdate('Y-m-d H:i:59');
  2566 		$now = gmdate('Y-m-d H:i:59');
  1681 		if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
  2567 		if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
  1682 			$post_status = 'future';
  2568 			$post_status = 'future';
       
  2569 	} elseif( 'future' == $post_status ) {
       
  2570 		$now = gmdate('Y-m-d H:i:59');
       
  2571 		if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
       
  2572 			$post_status = 'publish';
  1683 	}
  2573 	}
  1684 
  2574 
  1685 	if ( empty($comment_status) ) {
  2575 	if ( empty($comment_status) ) {
  1686 		if ( $update )
  2576 		if ( $update )
  1687 			$comment_status = 'closed';
  2577 			$comment_status = 'closed';
  1690 	}
  2580 	}
  1691 	if ( empty($ping_status) )
  2581 	if ( empty($ping_status) )
  1692 		$ping_status = get_option('default_ping_status');
  2582 		$ping_status = get_option('default_ping_status');
  1693 
  2583 
  1694 	if ( isset($to_ping) )
  2584 	if ( isset($to_ping) )
  1695 		$to_ping = preg_replace('|\s+|', "\n", $to_ping);
  2585 		$to_ping = sanitize_trackback_urls( $to_ping );
  1696 	else
  2586 	else
  1697 		$to_ping = '';
  2587 		$to_ping = '';
  1698 
  2588 
  1699 	if ( ! isset($pinged) )
  2589 	if ( ! isset($pinged) )
  1700 		$pinged = '';
  2590 		$pinged = '';
  1702 	if ( isset($post_parent) )
  2592 	if ( isset($post_parent) )
  1703 		$post_parent = (int) $post_parent;
  2593 		$post_parent = (int) $post_parent;
  1704 	else
  2594 	else
  1705 		$post_parent = 0;
  2595 		$post_parent = 0;
  1706 
  2596 
  1707 	if ( !empty($post_ID) ) {
  2597 	// Check the post_parent to see if it will cause a hierarchy loop
  1708 		if ( $post_parent == $post_ID ) {
  2598 	$post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
  1709 			// Post can't be its own parent
       
  1710 			$post_parent = 0;
       
  1711 		} elseif ( !empty($post_parent) ) {
       
  1712 			$parent_post = get_post($post_parent);
       
  1713 			// Check for circular dependency
       
  1714 			if ( $parent_post->post_parent == $post_ID )
       
  1715 				$post_parent = 0;
       
  1716 		}
       
  1717 	}
       
  1718 
  2599 
  1719 	if ( isset($menu_order) )
  2600 	if ( isset($menu_order) )
  1720 		$menu_order = (int) $menu_order;
  2601 		$menu_order = (int) $menu_order;
  1721 	else
  2602 	else
  1722 		$menu_order = 0;
  2603 		$menu_order = 0;
  1730 	$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' ) );
  2611 	$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' ) );
  1731 	$data = apply_filters('wp_insert_post_data', $data, $postarr);
  2612 	$data = apply_filters('wp_insert_post_data', $data, $postarr);
  1732 	$data = stripslashes_deep( $data );
  2613 	$data = stripslashes_deep( $data );
  1733 	$where = array( 'ID' => $post_ID );
  2614 	$where = array( 'ID' => $post_ID );
  1734 
  2615 
  1735 	if ($update) {
  2616 	if ( $update ) {
  1736 		do_action( 'pre_post_update', $post_ID );
  2617 		do_action( 'pre_post_update', $post_ID );
  1737 		if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  2618 		if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  1738 			if ( $wp_error )
  2619 			if ( $wp_error )
  1739 				return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  2620 				return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  1740 			else
  2621 			else
  1760 
  2641 
  1761 		// use the newly generated $post_ID
  2642 		// use the newly generated $post_ID
  1762 		$where = array( 'ID' => $post_ID );
  2643 		$where = array( 'ID' => $post_ID );
  1763 	}
  2644 	}
  1764 
  2645 
  1765 	if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending' ) ) ) {
  2646 	if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
  1766 		$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
  2647 		$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
  1767 		$wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  2648 		$wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  1768 	}
  2649 	}
  1769 
  2650 
  1770 	wp_set_post_categories( $post_ID, $post_category );
  2651 	if ( is_object_in_taxonomy($post_type, 'category') )
  1771 	// old-style tags_input
  2652 		wp_set_post_categories( $post_ID, $post_category );
  1772 	if ( !empty($tags_input) )
  2653 
       
  2654 	if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
  1773 		wp_set_post_tags( $post_ID, $tags_input );
  2655 		wp_set_post_tags( $post_ID, $tags_input );
  1774 	// new-style support for all tag-like taxonomies
  2656 
       
  2657 	// new-style support for all custom taxonomies
  1775 	if ( !empty($tax_input) ) {
  2658 	if ( !empty($tax_input) ) {
  1776 		foreach ( $tax_input as $taxonomy => $tags ) {
  2659 		foreach ( $tax_input as $taxonomy => $tags ) {
  1777 			wp_set_post_terms( $post_ID, $tags, $taxonomy );
  2660 			$taxonomy_obj = get_taxonomy($taxonomy);
       
  2661 			if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
       
  2662 				$tags = array_filter($tags);
       
  2663 			if ( current_user_can($taxonomy_obj->cap->assign_terms) )
       
  2664 				wp_set_post_terms( $post_ID, $tags, $taxonomy );
  1778 		}
  2665 		}
  1779 	}
  2666 	}
  1780 
  2667 
  1781 	$current_guid = get_post_field( 'guid', $post_ID );
  2668 	$current_guid = get_post_field( 'guid', $post_ID );
  1782 
  2669 
  1783 	if ( 'page' == $data['post_type'] )
  2670 	clean_post_cache( $post_ID );
  1784 		clean_page_cache($post_ID);
       
  1785 	else
       
  1786 		clean_post_cache($post_ID);
       
  1787 
  2671 
  1788 	// Set GUID
  2672 	// Set GUID
  1789 	if ( !$update && '' == $current_guid )
  2673 	if ( !$update && '' == $current_guid )
  1790 		$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  2674 		$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  1791 
  2675 
  1803 		update_post_meta($post_ID, '_wp_page_template',  $page_template);
  2687 		update_post_meta($post_ID, '_wp_page_template',  $page_template);
  1804 	}
  2688 	}
  1805 
  2689 
  1806 	wp_transition_post_status($data['post_status'], $previous_status, $post);
  2690 	wp_transition_post_status($data['post_status'], $previous_status, $post);
  1807 
  2691 
  1808 	if ( $update)
  2692 	if ( $update ) {
  1809 		do_action('edit_post', $post_ID, $post);
  2693 		do_action('edit_post', $post_ID, $post);
       
  2694 		$post_after = get_post($post_ID);
       
  2695 		do_action( 'post_updated', $post_ID, $post_after, $post_before);
       
  2696 	}
  1810 
  2697 
  1811 	do_action('save_post', $post_ID, $post);
  2698 	do_action('save_post', $post_ID, $post);
  1812 	do_action('wp_insert_post', $post_ID, $post);
  2699 	do_action('wp_insert_post', $post_ID, $post);
  1813 
  2700 
  1814 	return $post_ID;
  2701 	return $post_ID;
  1844 		$post_cats = $postarr['post_category'];
  2731 		$post_cats = $postarr['post_category'];
  1845 	else
  2732 	else
  1846 		$post_cats = $post['post_category'];
  2733 		$post_cats = $post['post_category'];
  1847 
  2734 
  1848 	// Drafts shouldn't be assigned a date unless explicitly done so by the user
  2735 	// Drafts shouldn't be assigned a date unless explicitly done so by the user
  1849 	if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
  2736 	if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
  1850 			 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  2737 			 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  1851 		$clear_date = true;
  2738 		$clear_date = true;
  1852 	else
  2739 	else
  1853 		$clear_date = false;
  2740 		$clear_date = false;
  1854 
  2741 
  1891 
  2778 
  1892 	$old_status = $post->post_status;
  2779 	$old_status = $post->post_status;
  1893 	$post->post_status = 'publish';
  2780 	$post->post_status = 'publish';
  1894 	wp_transition_post_status('publish', $old_status, $post);
  2781 	wp_transition_post_status('publish', $old_status, $post);
  1895 
  2782 
  1896 	// Update counts for the post's terms.
       
  1897 	foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
       
  1898 		$tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
       
  1899 		wp_update_term_count($tt_ids, $taxonomy);
       
  1900 	}
       
  1901 
       
  1902 	do_action('edit_post', $post_id, $post);
  2783 	do_action('edit_post', $post_id, $post);
  1903 	do_action('save_post', $post_id, $post);
  2784 	do_action('save_post', $post_id, $post);
  1904 	do_action('wp_insert_post', $post_id, $post);
  2785 	do_action('wp_insert_post', $post_id, $post);
  1905 }
  2786 }
  1906 
  2787 
  1926 		return;
  2807 		return;
  1927 
  2808 
  1928 	$time = strtotime( $post->post_date_gmt . ' GMT' );
  2809 	$time = strtotime( $post->post_date_gmt . ' GMT' );
  1929 
  2810 
  1930 	if ( $time > time() ) { // Uh oh, someone jumped the gun!
  2811 	if ( $time > time() ) { // Uh oh, someone jumped the gun!
  1931 		wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
  2812 		wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
  1932 		wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  2813 		wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  1933 		return;
  2814 		return;
  1934 	}
  2815 	}
  1935 
  2816 
  1936 	return wp_publish_post($post_id);
  2817 	return wp_publish_post($post_id);
  1937 }
  2818 }
  1938 
  2819 
  1939 
  2820 /**
  1940 /**
  2821  * Computes a unique slug for the post, when given the desired slug and some post details.
  1941  * Given the desired slug and some post details computes a unique slug for the post.
  2822  *
  1942  *
  2823  * @since 2.8.0
  1943  * @global wpdb $wpdb 
  2824  *
  1944  * @global WP_Rewrite $wp_rewrite 
  2825  * @global wpdb $wpdb
       
  2826  * @global WP_Rewrite $wp_rewrite
  1945  * @param string $slug the desired slug (post_name)
  2827  * @param string $slug the desired slug (post_name)
  1946  * @param integer $post_ID
  2828  * @param integer $post_ID
  1947  * @param string $post_status no uniqueness checks are made if the post is still draft or pending
  2829  * @param string $post_status no uniqueness checks are made if the post is still draft or pending
  1948  * @param string $post_type
  2830  * @param string $post_type
  1949  * @param integer $post_parent
  2831  * @param integer $post_parent
  1950  * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  2832  * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  1951  */
  2833  */
  1952 function wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
  2834 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
  1953 	if ( in_array( $post_status, array( 'draft', 'pending' ) ) )
  2835 	if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  1954 		return $slug;
  2836 		return $slug;
  1955 
  2837 
  1956 	global $wpdb, $wp_rewrite;
  2838 	global $wpdb, $wp_rewrite;
  1957 
  2839 
  1958 	$feeds = $wp_rewrite->feeds;
  2840 	$feeds = $wp_rewrite->feeds;
  1959 	if ( !is_array($feeds) )
  2841 	if ( ! is_array( $feeds ) )
  1960 		$feeds = array();
  2842 		$feeds = array();
  1961 
  2843 
  1962 	$hierarchical_post_types = apply_filters('hierarchical_post_types', array('page'));
  2844 	$hierarchical_post_types = get_post_types( array('hierarchical' => true) );
  1963 	if ( 'attachment' == $post_type ) {
  2845 	if ( 'attachment' == $post_type ) {
  1964 		// Attachment slugs must be unique across all types.
  2846 		// Attachment slugs must be unique across all types.
  1965 		$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  2847 		$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  1966 		$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
  2848 		$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
  1967 
  2849 
  1968 		if ( $post_name_check || in_array($slug, $feeds) ) {
  2850 		if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
  1969 			$suffix = 2;
  2851 			$suffix = 2;
  1970 			do {
  2852 			do {
  1971 				$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
  2853 				$alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  1972 				$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID));
  2854 				$post_name_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_post_name, $post_ID ) );
  1973 				$suffix++;
  2855 				$suffix++;
  1974 			} while ($post_name_check);
  2856 			} while ( $post_name_check );
  1975 			$slug = $alt_post_name;
  2857 			$slug = $alt_post_name;
  1976 		}
  2858 		}
  1977 	} elseif ( in_array($post_type, $hierarchical_post_types) ) {
  2859 	} elseif ( in_array( $post_type, $hierarchical_post_types ) ) {
  1978 		// Page slugs must be unique within their own trees.  Pages are in a
  2860 		// Page slugs must be unique within their own trees. Pages are in a separate
  1979 		// separate namespace than posts so page slugs are allowed to overlap post slugs.
  2861 		// namespace than posts so page slugs are allowed to overlap post slugs.
  1980 		$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";
  2862 		$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";
  1981 		$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID, $post_parent));
  2863 		$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) );
  1982 
  2864 
  1983 		if ( $post_name_check || in_array($slug, $feeds) ) {
  2865 		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 ) ) {
  1984 			$suffix = 2;
  2866 			$suffix = 2;
  1985 			do {
  2867 			do {
  1986 				$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
  2868 				$alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  1987 				$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID, $post_parent));
  2869 				$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) );
  1988 				$suffix++;
  2870 				$suffix++;
  1989 			} while ($post_name_check);
  2871 			} while ( $post_name_check );
  1990 			$slug = $alt_post_name;
  2872 			$slug = $alt_post_name;
  1991 		}
  2873 		}
  1992 	} else {
  2874 	} else {
  1993 		// Post slugs must be unique across all posts.
  2875 		// Post slugs must be unique across all posts.
  1994 		$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  2876 		$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  1995 		$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_type, $post_ID));
  2877 		$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
  1996 
  2878 
  1997 		if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
  2879 		if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
  1998 			$suffix = 2;
  2880 			$suffix = 2;
  1999 			do {
  2881 			do {
  2000 				$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
  2882 				$alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  2001 				$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID));
  2883 				$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
  2002 				$suffix++;
  2884 				$suffix++;
  2003 			} while ($post_name_check);
  2885 			} while ( $post_name_check );
  2004 			$slug = $alt_post_name;
  2886 			$slug = $alt_post_name;
  2005 		}
  2887 		}
  2006 	}
  2888 	}
  2007 
  2889 
  2008 	return $slug;
  2890 	return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent );
  2009 }
  2891 }
  2010 
  2892 
  2011 /**
  2893 /**
  2012  * Adds tags to a post.
  2894  * Adds tags to a post.
  2013  *
  2895  *
  2023  */
  2905  */
  2024 function wp_add_post_tags($post_id = 0, $tags = '') {
  2906 function wp_add_post_tags($post_id = 0, $tags = '') {
  2025 	return wp_set_post_tags($post_id, $tags, true);
  2907 	return wp_set_post_tags($post_id, $tags, true);
  2026 }
  2908 }
  2027 
  2909 
  2028 
       
  2029 /**
  2910 /**
  2030  * Set the tags for a post.
  2911  * Set the tags for a post.
  2031  *
  2912  *
  2032  * @since 2.3.0
  2913  * @since 2.3.0
  2033  * @uses wp_set_object_terms() Sets the tags for the post.
  2914  * @uses wp_set_object_terms() Sets the tags for the post.
  2034  *
  2915  *
  2035  * @param int $post_id Post ID.
  2916  * @param int $post_id Post ID.
  2036  * @param string $tags The tags to set for the post, separated by commas.
  2917  * @param string $tags The tags to set for the post, separated by commas.
  2037  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2918  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2038  * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
  2919  * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2039  */
  2920  */
  2040 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  2921 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  2041 	return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
  2922 	return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
  2042 }
  2923 }
  2043 
  2924 
  2047  * @since 2.8.0
  2928  * @since 2.8.0
  2048  * @uses wp_set_object_terms() Sets the tags for the post.
  2929  * @uses wp_set_object_terms() Sets the tags for the post.
  2049  *
  2930  *
  2050  * @param int $post_id Post ID.
  2931  * @param int $post_id Post ID.
  2051  * @param string $tags The tags to set for the post, separated by commas.
  2932  * @param string $tags The tags to set for the post, separated by commas.
       
  2933  * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'.
  2052  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2934  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
  2053  * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
  2935  * @return mixed Array of affected term IDs. WP_Error or false on failure.
  2054  */
  2936  */
  2055 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  2937 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  2056 	$post_id = (int) $post_id;
  2938 	$post_id = (int) $post_id;
  2057 
  2939 
  2058 	if ( !$post_id )
  2940 	if ( !$post_id )
  2059 		return false;
  2941 		return false;
  2060 
  2942 
  2061 	if ( empty($tags) )
  2943 	if ( empty($tags) )
  2062 		$tags = array();
  2944 		$tags = array();
  2063 
  2945 
  2064 	$tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
  2946 	if ( ! is_array( $tags ) ) {
  2065 	wp_set_object_terms($post_id, $tags, $taxonomy, $append);
  2947 		$comma = _x( ',', 'tag delimiter' );
       
  2948 		if ( ',' !== $comma )
       
  2949 			$tags = str_replace( $comma, ',', $tags );
       
  2950 		$tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
       
  2951 	}
       
  2952 
       
  2953 	// Hierarchical taxonomies must always pass IDs rather than names so that children with the same
       
  2954 	// names but different parents aren't confused.
       
  2955 	if ( is_taxonomy_hierarchical( $taxonomy ) ) {
       
  2956 		$tags = array_map( 'intval', $tags );
       
  2957 		$tags = array_unique( $tags );
       
  2958 	}
       
  2959 
       
  2960 	return wp_set_object_terms($post_id, $tags, $taxonomy, $append);
  2066 }
  2961 }
  2067 
  2962 
  2068 /**
  2963 /**
  2069  * Set categories for a post.
  2964  * Set categories for a post.
  2070  *
  2965  *
  2077  * @param array $post_categories Optional. List of categories.
  2972  * @param array $post_categories Optional. List of categories.
  2078  * @return bool|mixed
  2973  * @return bool|mixed
  2079  */
  2974  */
  2080 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
  2975 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
  2081 	$post_ID = (int) $post_ID;
  2976 	$post_ID = (int) $post_ID;
       
  2977 	$post_type = get_post_type( $post_ID );
       
  2978 	$post_status = get_post_status( $post_ID );
  2082 	// If $post_categories isn't already an array, make it one:
  2979 	// If $post_categories isn't already an array, make it one:
  2083 	if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
  2980 	if ( !is_array($post_categories) || empty($post_categories) ) {
  2084 		$post_categories = array(get_option('default_category'));
  2981 		if ( 'post' == $post_type && 'auto-draft' != $post_status )
  2085 	else if ( 1 == count($post_categories) && '' == $post_categories[0] )
  2982 			$post_categories = array( get_option('default_category') );
       
  2983 		else
       
  2984 			$post_categories = array();
       
  2985 	} else if ( 1 == count($post_categories) && '' == reset($post_categories) ) {
  2086 		return true;
  2986 		return true;
  2087 
  2987 	}
  2088 	$post_categories = array_map('intval', $post_categories);
  2988 
  2089 	$post_categories = array_unique($post_categories);
  2989 	if ( !empty($post_categories) ) {
       
  2990 		$post_categories = array_map('intval', $post_categories);
       
  2991 		$post_categories = array_unique($post_categories);
       
  2992 	}
  2090 
  2993 
  2091 	return wp_set_object_terms($post_ID, $post_categories, 'category');
  2994 	return wp_set_object_terms($post_ID, $post_categories, 'category');
  2092 }
  2995 }
  2093 
  2996 
  2094 /**
  2997 /**
  2108  * @since 2.3.0
  3011  * @since 2.3.0
  2109  * @link http://codex.wordpress.org/Post_Status_Transitions
  3012  * @link http://codex.wordpress.org/Post_Status_Transitions
  2110  *
  3013  *
  2111  * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
  3014  * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
  2112  *  $post if there is a status change.
  3015  *  $post if there is a status change.
  2113  * @uses do_action() Calls '${old_status}_to_$new_status' on $post if there is a status change.
  3016  * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change.
  2114  * @uses do_action() Calls '${new_status}_$post->post_type' on post ID and $post.
  3017  * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post.
  2115  *
  3018  *
  2116  * @param string $new_status Transition to this post status.
  3019  * @param string $new_status Transition to this post status.
  2117  * @param string $old_status Previous post status.
  3020  * @param string $old_status Previous post status.
  2118  * @param object $post Post data.
  3021  * @param object $post Post data.
  2119  */
  3022  */
  2120 function wp_transition_post_status($new_status, $old_status, $post) {
  3023 function wp_transition_post_status($new_status, $old_status, $post) {
  2121 	do_action('transition_post_status', $new_status, $old_status, $post);
  3024 	do_action('transition_post_status', $new_status, $old_status, $post);
  2122 	do_action("${old_status}_to_$new_status", $post);
  3025 	do_action("{$old_status}_to_{$new_status}", $post);
  2123 	do_action("${new_status}_$post->post_type", $post->ID, $post);
  3026 	do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
  2124 }
  3027 }
  2125 
  3028 
  2126 //
  3029 //
  2127 // Trackback and ping functions
  3030 // Trackback and ping functions
  2128 //
  3031 //
  2167 
  3070 
  2168 	foreach ( $custom_fields as $key => $val ) {
  3071 	foreach ( $custom_fields as $key => $val ) {
  2169 		if ( 'enclosure' != $key || !is_array( $val ) )
  3072 		if ( 'enclosure' != $key || !is_array( $val ) )
  2170 			continue;
  3073 			continue;
  2171 		foreach( $val as $enc ) {
  3074 		foreach( $val as $enc ) {
  2172 			$enclosure = split( "\n", $enc );
  3075 			$enclosure = explode( "\n", $enc );
  2173 			$pung[] = trim( $enclosure[ 0 ] );
  3076 			$pung[] = trim( $enclosure[ 0 ] );
  2174 		}
  3077 		}
  2175 	}
  3078 	}
  2176 	$pung = apply_filters('get_enclosed', $pung);
  3079 	$pung = apply_filters('get_enclosed', $pung, $post_id);
  2177 	return $pung;
  3080 	return $pung;
  2178 }
  3081 }
  2179 
  3082 
  2180 /**
  3083 /**
  2181  * Retrieve URLs already pinged for a post.
  3084  * Retrieve URLs already pinged for a post.
  2205  * @return array
  3108  * @return array
  2206  */
  3109  */
  2207 function get_to_ping($post_id) {
  3110 function get_to_ping($post_id) {
  2208 	global $wpdb;
  3111 	global $wpdb;
  2209 	$to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3112 	$to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
  2210 	$to_ping = trim($to_ping);
  3113 	$to_ping = sanitize_trackback_urls( $to_ping );
  2211 	$to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
  3114 	$to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
  2212 	$to_ping = apply_filters('get_to_ping',  $to_ping);
  3115 	$to_ping = apply_filters('get_to_ping',  $to_ping);
  2213 	return $to_ping;
  3116 	return $to_ping;
  2214 }
  3117 }
  2215 
  3118 
  2257  * @return array List of page IDs.
  3160  * @return array List of page IDs.
  2258  */
  3161  */
  2259 function get_all_page_ids() {
  3162 function get_all_page_ids() {
  2260 	global $wpdb;
  3163 	global $wpdb;
  2261 
  3164 
  2262 	if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
  3165 	$page_ids = wp_cache_get('all_page_ids', 'posts');
       
  3166 	if ( ! is_array( $page_ids ) ) {
  2263 		$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
  3167 		$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
  2264 		wp_cache_add('all_page_ids', $page_ids, 'posts');
  3168 		wp_cache_add('all_page_ids', $page_ids, 'posts');
  2265 	}
  3169 	}
  2266 
  3170 
  2267 	return $page_ids;
  3171 	return $page_ids;
  2276  * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
  3180  * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
  2277  * @param string $filter How the return value should be filtered.
  3181  * @param string $filter How the return value should be filtered.
  2278  * @return mixed Page data.
  3182  * @return mixed Page data.
  2279  */
  3183  */
  2280 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
  3184 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
  2281 	if ( empty($page) ) {
  3185 	$p = get_post($page, $output, $filter);
  2282 		if ( isset( $GLOBALS['post'] ) && isset( $GLOBALS['post']->ID ) ) {
  3186 	return $p;
  2283 			return get_post($GLOBALS['post'], $output, $filter);
       
  2284 		} else {
       
  2285 			$page = null;
       
  2286 			return $page;
       
  2287 		}
       
  2288 	}
       
  2289 
       
  2290 	$the_page = get_post($page, $output, $filter);
       
  2291 	return $the_page;
       
  2292 }
  3187 }
  2293 
  3188 
  2294 /**
  3189 /**
  2295  * Retrieves a page given its path.
  3190  * Retrieves a page given its path.
  2296  *
  3191  *
  2297  * @since 2.1.0
  3192  * @since 2.1.0
  2298  * @uses $wpdb
  3193  * @uses $wpdb
  2299  *
  3194  *
  2300  * @param string $page_path Page path
  3195  * @param string $page_path Page path
  2301  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
  3196  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
       
  3197  * @param string $post_type Optional. Post type. Default page.
  2302  * @return mixed Null when complete.
  3198  * @return mixed Null when complete.
  2303  */
  3199  */
  2304 function get_page_by_path($page_path, $output = OBJECT) {
  3200 function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') {
  2305 	global $wpdb;
  3201 	global $wpdb;
       
  3202 
  2306 	$page_path = rawurlencode(urldecode($page_path));
  3203 	$page_path = rawurlencode(urldecode($page_path));
  2307 	$page_path = str_replace('%2F', '/', $page_path);
  3204 	$page_path = str_replace('%2F', '/', $page_path);
  2308 	$page_path = str_replace('%20', ' ', $page_path);
  3205 	$page_path = str_replace('%20', ' ', $page_path);
  2309 	$page_paths = '/' . trim($page_path, '/');
  3206 	$parts = explode( '/', trim( $page_path, '/' ) );
  2310 	$leaf_path  = sanitize_title(basename($page_paths));
  3207 	$parts = array_map( 'esc_sql', $parts );
  2311 	$page_paths = explode('/', $page_paths);
  3208 	$parts = array_map( 'sanitize_title_for_query', $parts );
  2312 	$full_path = '';
  3209 
  2313 	foreach( (array) $page_paths as $pathdir)
  3210 	$in_string = "'". implode( "','", $parts ) . "'";
  2314 		$full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
  3211 	$post_type_sql = $post_type;
  2315 
  3212 	$wpdb->escape_by_ref( $post_type_sql );
  2316 	$pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = 'page' OR post_type = 'attachment')", $leaf_path ));
  3213 	$pages = $wpdb->get_results( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K );
  2317 
  3214 
  2318 	if ( empty($pages) )
  3215 	$revparts = array_reverse( $parts );
  2319 		return null;
  3216 
  2320 
  3217 	$foundid = 0;
  2321 	foreach ($pages as $page) {
  3218 	foreach ( (array) $pages as $page ) {
  2322 		$path = '/' . $leaf_path;
  3219 		if ( $page->post_name == $revparts[0] ) {
  2323 		$curpage = $page;
  3220 			$count = 0;
  2324 		while ($curpage->post_parent != 0) {
  3221 			$p = $page;
  2325 			$curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type='page'", $curpage->post_parent ));
  3222 			while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
  2326 			$path = '/' . $curpage->post_name . $path;
  3223 				$count++;
       
  3224 				$parent = $pages[ $p->post_parent ];
       
  3225 				if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
       
  3226 					break;
       
  3227 				$p = $parent;
       
  3228 			}
       
  3229 
       
  3230 			if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
       
  3231 				$foundid = $page->ID;
       
  3232 				break;
       
  3233 			}
  2327 		}
  3234 		}
  2328 
  3235 	}
  2329 		if ( $path == $full_path )
  3236 
  2330 			return get_page($page->ID, $output);
  3237 	if ( $foundid )
  2331 	}
  3238 		return get_page( $foundid, $output );
  2332 
  3239 
  2333 	return null;
  3240 	return null;
  2334 }
  3241 }
  2335 
  3242 
  2336 /**
  3243 /**
  2338  *
  3245  *
  2339  * @since 2.1.0
  3246  * @since 2.1.0
  2340  * @uses $wpdb
  3247  * @uses $wpdb
  2341  *
  3248  *
  2342  * @param string $page_title Page title
  3249  * @param string $page_title Page title
  2343  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
  3250  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
       
  3251  * @param string $post_type Optional. Post type. Default page.
  2344  * @return mixed
  3252  * @return mixed
  2345  */
  3253  */
  2346 function get_page_by_title($page_title, $output = OBJECT) {
  3254 function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) {
  2347 	global $wpdb;
  3255 	global $wpdb;
  2348 	$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
  3256 	$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) );
  2349 	if ( $page )
  3257 	if ( $page )
  2350 		return get_page($page, $output);
  3258 		return get_page($page, $output);
  2351 
  3259 
  2352 	return null;
  3260 	return null;
  2353 }
  3261 }
  2383  * It uses auxiliary structure to hold parent-children relationships and
  3291  * It uses auxiliary structure to hold parent-children relationships and
  2384  * runs in O(N) complexity
  3292  * runs in O(N) complexity
  2385  *
  3293  *
  2386  * @since 2.0.0
  3294  * @since 2.0.0
  2387  *
  3295  *
  2388  * @param array $posts Posts array.
  3296  * @param array $pages Posts array.
  2389  * @param int $parent Parent page ID.
  3297  * @param int $page_id Parent page ID.
  2390  * @return array A list arranged by hierarchy. Children immediately follow their parents.
  3298  * @return array A list arranged by hierarchy. Children immediately follow their parents.
  2391  */
  3299  */
  2392 function &get_page_hierarchy( &$pages, $page_id = 0 ) {
  3300 function &get_page_hierarchy( &$pages, $page_id = 0 ) {
  2393 
       
  2394 	if ( empty( $pages ) ) {
  3301 	if ( empty( $pages ) ) {
  2395 		$return = array();
  3302 		$result = array();
  2396 		return $return;
  3303 		return $result;
  2397 	}
  3304 	}
  2398 
  3305 
  2399 	$children = array();
  3306 	$children = array();
  2400 	foreach ( (array) $pages as $p ) {
  3307 	foreach ( (array) $pages as $p ) {
  2401 
       
  2402 		$parent_id = intval( $p->post_parent );
  3308 		$parent_id = intval( $p->post_parent );
  2403 		$children[ $parent_id ][] = $p;
  3309 		$children[ $parent_id ][] = $p;
  2404 	 }
  3310 	}
  2405 
  3311 
  2406 	 $result = array();
  3312 	$result = array();
  2407 	 _page_traverse_name( $page_id, $children, $result );
  3313 	_page_traverse_name( $page_id, $children, $result );
  2408 
  3314 
  2409 	return $result;
  3315 	return $result;
  2410 }
  3316 }
  2411 
  3317 
  2412 /**
  3318 /**
  2413  * function to traverse and return all the nested children post names of a root page.
  3319  * function to traverse and return all the nested children post names of a root page.
  2414  * $children contains parent-chilren relations
  3320  * $children contains parent-children relations
  2415  *
  3321  *
       
  3322  * @since 2.9.0
  2416  */
  3323  */
  2417 function _page_traverse_name( $page_id, &$children, &$result ){
  3324 function _page_traverse_name( $page_id, &$children, &$result ){
  2418 
       
  2419 	if ( isset( $children[ $page_id ] ) ){
  3325 	if ( isset( $children[ $page_id ] ) ){
  2420 
       
  2421 		foreach( (array)$children[ $page_id ] as $child ) {
  3326 		foreach( (array)$children[ $page_id ] as $child ) {
  2422 
       
  2423 			$result[ $child->ID ] = $child->post_name;
  3327 			$result[ $child->ID ] = $child->post_name;
  2424 			_page_traverse_name( $child->ID, $children, $result );
  3328 			_page_traverse_name( $child->ID, $children, $result );
  2425 		}
  3329 		}
  2426 	}
  3330 	}
  2427 }
  3331 }
  2431  *
  3335  *
  2432  * Sub pages will be in the "directory" under the parent page post name.
  3336  * Sub pages will be in the "directory" under the parent page post name.
  2433  *
  3337  *
  2434  * @since 1.5.0
  3338  * @since 1.5.0
  2435  *
  3339  *
  2436  * @param int $page_id Page ID.
  3340  * @param mixed $page Page object or page ID.
  2437  * @return string Page URI.
  3341  * @return string Page URI.
  2438  */
  3342  */
  2439 function get_page_uri($page_id) {
  3343 function get_page_uri($page) {
  2440 	$page = get_page($page_id);
  3344 	if ( ! is_object($page) )
       
  3345 		$page = get_page($page);
  2441 	$uri = $page->post_name;
  3346 	$uri = $page->post_name;
  2442 
  3347 
  2443 	// A page cannot be it's own parent.
  3348 	// A page cannot be it's own parent.
  2444 	if ( $page->post_parent == $page->ID )
  3349 	if ( $page->post_parent == $page->ID )
  2445 		return $uri;
  3350 		return $uri;
  2469 	global $wpdb;
  3374 	global $wpdb;
  2470 
  3375 
  2471 	$defaults = array(
  3376 	$defaults = array(
  2472 		'child_of' => 0, 'sort_order' => 'ASC',
  3377 		'child_of' => 0, 'sort_order' => 'ASC',
  2473 		'sort_column' => 'post_title', 'hierarchical' => 1,
  3378 		'sort_column' => 'post_title', 'hierarchical' => 1,
  2474 		'exclude' => '', 'include' => '',
  3379 		'exclude' => array(), 'include' => array(),
  2475 		'meta_key' => '', 'meta_value' => '',
  3380 		'meta_key' => '', 'meta_value' => '',
  2476 		'authors' => '', 'parent' => -1, 'exclude_tree' => '',
  3381 		'authors' => '', 'parent' => -1, 'exclude_tree' => '',
  2477 		'number' => '', 'offset' => 0
  3382 		'number' => '', 'offset' => 0,
       
  3383 		'post_type' => 'page', 'post_status' => 'publish',
  2478 	);
  3384 	);
  2479 
  3385 
  2480 	$r = wp_parse_args( $args, $defaults );
  3386 	$r = wp_parse_args( $args, $defaults );
  2481 	extract( $r, EXTR_SKIP );
  3387 	extract( $r, EXTR_SKIP );
  2482 	$number = (int) $number;
  3388 	$number = (int) $number;
  2483 	$offset = (int) $offset;
  3389 	$offset = (int) $offset;
       
  3390 
       
  3391 	// Make sure the post type is hierarchical
       
  3392 	$hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
       
  3393 	if ( !in_array( $post_type, $hierarchical_post_types ) )
       
  3394 		return false;
       
  3395 
       
  3396 	// Make sure we have a valid post status
       
  3397 	if ( !is_array( $post_status ) )
       
  3398 		$post_status = explode( ',', $post_status );
       
  3399 	if ( array_diff( $post_status, get_post_stati() ) )
       
  3400 		return false;
  2484 
  3401 
  2485 	$cache = array();
  3402 	$cache = array();
  2486 	$key = md5( serialize( compact(array_keys($defaults)) ) );
  3403 	$key = md5( serialize( compact(array_keys($defaults)) ) );
  2487 	if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
  3404 	if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
  2488 		if ( is_array($cache) && isset( $cache[ $key ] ) ) {
  3405 		if ( is_array($cache) && isset( $cache[ $key ] ) ) {
  2500 		$parent = -1;
  3417 		$parent = -1;
  2501 		$exclude = '';
  3418 		$exclude = '';
  2502 		$meta_key = '';
  3419 		$meta_key = '';
  2503 		$meta_value = '';
  3420 		$meta_value = '';
  2504 		$hierarchical = false;
  3421 		$hierarchical = false;
  2505 		$incpages = preg_split('/[\s,]+/',$include);
  3422 		$incpages = wp_parse_id_list( $include );
  2506 		if ( count($incpages) ) {
  3423 		if ( ! empty( $incpages ) ) {
  2507 			foreach ( $incpages as $incpage ) {
  3424 			foreach ( $incpages as $incpage ) {
  2508 				if (empty($inclusions))
  3425 				if (empty($inclusions))
  2509 					$inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
  3426 					$inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
  2510 				else
  3427 				else
  2511 					$inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
  3428 					$inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
  2515 	if (!empty($inclusions))
  3432 	if (!empty($inclusions))
  2516 		$inclusions .= ')';
  3433 		$inclusions .= ')';
  2517 
  3434 
  2518 	$exclusions = '';
  3435 	$exclusions = '';
  2519 	if ( !empty($exclude) ) {
  3436 	if ( !empty($exclude) ) {
  2520 		$expages = preg_split('/[\s,]+/',$exclude);
  3437 		$expages = wp_parse_id_list( $exclude );
  2521 		if ( count($expages) ) {
  3438 		if ( ! empty( $expages ) ) {
  2522 			foreach ( $expages as $expage ) {
  3439 			foreach ( $expages as $expage ) {
  2523 				if (empty($exclusions))
  3440 				if (empty($exclusions))
  2524 					$exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
  3441 					$exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
  2525 				else
  3442 				else
  2526 					$exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
  3443 					$exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
  2532 
  3449 
  2533 	$author_query = '';
  3450 	$author_query = '';
  2534 	if (!empty($authors)) {
  3451 	if (!empty($authors)) {
  2535 		$post_authors = preg_split('/[\s,]+/',$authors);
  3452 		$post_authors = preg_split('/[\s,]+/',$authors);
  2536 
  3453 
  2537 		if ( count($post_authors) ) {
  3454 		if ( ! empty( $post_authors ) ) {
  2538 			foreach ( $post_authors as $post_author ) {
  3455 			foreach ( $post_authors as $post_author ) {
  2539 				//Do we have an author id or an author login?
  3456 				//Do we have an author id or an author login?
  2540 				if ( 0 == intval($post_author) ) {
  3457 				if ( 0 == intval($post_author) ) {
  2541 					$post_author = get_userdatabylogin($post_author);
  3458 					$post_author = get_user_by('login', $post_author);
  2542 					if ( empty($post_author) )
  3459 					if ( empty($post_author) )
  2543 						continue;
  3460 						continue;
  2544 					if ( empty($post_author->ID) )
  3461 					if ( empty($post_author->ID) )
  2545 						continue;
  3462 						continue;
  2546 					$post_author = $post_author->ID;
  3463 					$post_author = $post_author->ID;
  2572 	}
  3489 	}
  2573 
  3490 
  2574 	if ( $parent >= 0 )
  3491 	if ( $parent >= 0 )
  2575 		$where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
  3492 		$where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
  2576 
  3493 
  2577 	$query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
  3494 	if ( 1 == count( $post_status ) ) {
       
  3495 		$where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) );
       
  3496 	} else {
       
  3497 		$post_status = implode( "', '", $post_status );
       
  3498 		$where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type );
       
  3499 	}
       
  3500 
       
  3501 	$orderby_array = array();
       
  3502 	$allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
       
  3503 						  'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
       
  3504 						  'ID', 'rand', 'comment_count');
       
  3505 	foreach ( explode( ',', $sort_column ) as $orderby ) {
       
  3506 		$orderby = trim( $orderby );
       
  3507 		if ( !in_array( $orderby, $allowed_keys ) )
       
  3508 			continue;
       
  3509 
       
  3510 		switch ( $orderby ) {
       
  3511 			case 'menu_order':
       
  3512 				break;
       
  3513 			case 'ID':
       
  3514 				$orderby = "$wpdb->posts.ID";
       
  3515 				break;
       
  3516 			case 'rand':
       
  3517 				$orderby = 'RAND()';
       
  3518 				break;
       
  3519 			case 'comment_count':
       
  3520 				$orderby = "$wpdb->posts.comment_count";
       
  3521 				break;
       
  3522 			default:
       
  3523 				if ( 0 === strpos( $orderby, 'post_' ) )
       
  3524 					$orderby = "$wpdb->posts." . $orderby;
       
  3525 				else
       
  3526 					$orderby = "$wpdb->posts.post_" . $orderby;
       
  3527 		}
       
  3528 
       
  3529 		$orderby_array[] = $orderby;
       
  3530 
       
  3531 	}
       
  3532 	$sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
       
  3533 
       
  3534 	$sort_order = strtoupper( $sort_order );
       
  3535 	if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) )
       
  3536 		$sort_order = 'ASC';
       
  3537 
       
  3538 	$query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
  2578 	$query .= $author_query;
  3539 	$query .= $author_query;
  2579 	$query .= " ORDER BY " . $sort_column . " " . $sort_order ;
  3540 	$query .= " ORDER BY " . $sort_column . " " . $sort_order ;
  2580 
  3541 
  2581 	if ( !empty($number) )
  3542 	if ( !empty($number) )
  2582 		$query .= ' LIMIT ' . $offset . ',' . $number;
  3543 		$query .= ' LIMIT ' . $offset . ',' . $number;
  2593 	for ($i = 0; $i < $num_pages; $i++) {
  3554 	for ($i = 0; $i < $num_pages; $i++) {
  2594 		$pages[$i] = sanitize_post($pages[$i], 'raw');
  3555 		$pages[$i] = sanitize_post($pages[$i], 'raw');
  2595 	}
  3556 	}
  2596 
  3557 
  2597 	// Update cache.
  3558 	// Update cache.
  2598 	update_page_cache($pages);
  3559 	update_post_cache( $pages );
  2599 
  3560 
  2600 	if ( $child_of || $hierarchical )
  3561 	if ( $child_of || $hierarchical )
  2601 		$pages = & get_page_children($child_of, $pages);
  3562 		$pages = & get_page_children($child_of, $pages);
  2602 
  3563 
  2603 	if ( !empty($exclude_tree) ) {
  3564 	if ( !empty($exclude_tree) ) {
  2633  *
  3594  *
  2634  * @param string $url URL to check
  3595  * @param string $url URL to check
  2635  * @return bool True on success, false on failure.
  3596  * @return bool True on success, false on failure.
  2636  */
  3597  */
  2637 function is_local_attachment($url) {
  3598 function is_local_attachment($url) {
  2638 	if (strpos($url, get_bloginfo('url')) === false)
  3599 	if (strpos($url, home_url()) === false)
  2639 		return false;
  3600 		return false;
  2640 	if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
  3601 	if (strpos($url, home_url('/?attachment_id=')) !== false)
  2641 		return true;
  3602 		return true;
  2642 	if ( $id = url_to_postid($url) ) {
  3603 	if ( $id = url_to_postid($url) ) {
  2643 		$post = & get_post($id);
  3604 		$post = & get_post($id);
  2644 		if ( 'attachment' == $post->post_type )
  3605 		if ( 'attachment' == $post->post_type )
  2645 			return true;
  3606 			return true;
  2683  * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
  3644  * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
  2684  * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
  3645  * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
  2685  *
  3646  *
  2686  * @param string|array $object Arguments to override defaults.
  3647  * @param string|array $object Arguments to override defaults.
  2687  * @param string $file Optional filename.
  3648  * @param string $file Optional filename.
  2688  * @param int $post_parent Parent post ID.
  3649  * @param int $parent Parent post ID.
  2689  * @return int Attachment ID.
  3650  * @return int Attachment ID.
  2690  */
  3651  */
  2691 function wp_insert_attachment($object, $file = false, $parent = 0) {
  3652 function wp_insert_attachment($object, $file = false, $parent = 0) {
  2692 	global $wpdb, $user_ID;
  3653 	global $wpdb, $user_ID;
  2693 
  3654 
  2694 	$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  3655 	$defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_ID,
  2695 		'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  3656 		'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  2696 		'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
  3657 		'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
  2697 		'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
  3658 		'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
  2698 
  3659 
  2699 	$object = wp_parse_args($object, $defaults);
  3660 	$object = wp_parse_args($object, $defaults);
  2700 	if ( !empty($parent) )
  3661 	if ( !empty($parent) )
  2701 		$object['post_parent'] = $parent;
  3662 		$object['post_parent'] = $parent;
  2702 
  3663 
       
  3664 	unset( $object[ 'filter' ] );
       
  3665 
  2703 	$object = sanitize_post($object, 'db');
  3666 	$object = sanitize_post($object, 'db');
  2704 
  3667 
  2705 	// export array as variables
  3668 	// export array as variables
  2706 	extract($object, EXTR_SKIP);
  3669 	extract($object, EXTR_SKIP);
  2707 
  3670 
  2708 	// Make sure we set a valid category
       
  2709 	if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
       
  2710 		$post_category = array(get_option('default_category'));
       
  2711 	}
       
  2712 
       
  2713 	if ( empty($post_author) )
  3671 	if ( empty($post_author) )
  2714 		$post_author = $user_ID;
  3672 		$post_author = $user_ID;
  2715 
  3673 
  2716 	$post_type = 'attachment';
  3674 	$post_type = 'attachment';
  2717 	$post_status = 'inherit';
  3675 
       
  3676 	if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) )
       
  3677 		$post_status = 'inherit';
       
  3678 
       
  3679 	// Make sure we set a valid category.
       
  3680 	if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
       
  3681 		// 'post' requires at least one category.
       
  3682 		if ( 'post' == $post_type )
       
  3683 			$post_category = array( get_option('default_category') );
       
  3684 		else
       
  3685 			$post_category = array();
       
  3686 	}
  2718 
  3687 
  2719 	// Are we updating or creating?
  3688 	// Are we updating or creating?
  2720 	if ( !empty($ID) ) {
  3689 	if ( !empty($ID) ) {
  2721 		$update = true;
  3690 		$update = true;
  2722 		$post_ID = (int) $ID;
  3691 		$post_ID = (int) $ID;
  2801 	wp_set_post_categories($post_ID, $post_category);
  3770 	wp_set_post_categories($post_ID, $post_category);
  2802 
  3771 
  2803 	if ( $file )
  3772 	if ( $file )
  2804 		update_attached_file( $post_ID, $file );
  3773 		update_attached_file( $post_ID, $file );
  2805 
  3774 
  2806 	clean_post_cache($post_ID);
  3775 	clean_post_cache( $post_ID );
  2807 
  3776 
  2808 	if ( isset($post_parent) && $post_parent < 0 )
  3777 	if ( ! empty( $context ) )
  2809 		add_post_meta($post_ID, '_wp_attachment_temp_parent', $post_parent, true);
  3778 		add_post_meta( $post_ID, '_wp_attachment_context', $context, true );
  2810 
  3779 
  2811 	if ( $update) {
  3780 	if ( $update) {
  2812 		do_action('edit_attachment', $post_ID);
  3781 		do_action('edit_attachment', $post_ID);
  2813 	} else {
  3782 	} else {
  2814 		do_action('add_attachment', $post_ID);
  3783 		do_action('add_attachment', $post_ID);
  2816 
  3785 
  2817 	return $post_ID;
  3786 	return $post_ID;
  2818 }
  3787 }
  2819 
  3788 
  2820 /**
  3789 /**
  2821  * Delete an attachment.
  3790  * Trashes or deletes an attachment.
  2822  *
  3791  *
  2823  * Will remove the file also, when the attachment is removed. Removes all post
  3792  * When an attachment is permanently deleted, the file will also be removed.
  2824  * meta fields, taxonomy, comments, etc associated with the attachment (except
  3793  * Deletion removes all post meta fields, taxonomy, comments, etc. associated
  2825  * the main post).
  3794  * with the attachment (except the main post).
       
  3795  *
       
  3796  * The attachment is moved to the trash instead of permanently deleted unless trash
       
  3797  * for media is disabled, item is already in the trash, or $force_delete is true.
  2826  *
  3798  *
  2827  * @since 2.0.0
  3799  * @since 2.0.0
  2828  * @uses $wpdb
  3800  * @uses $wpdb
  2829  * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
  3801  * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
  2830  *
  3802  *
  2831  * @param int $postid Attachment ID.
  3803  * @param int $post_id Attachment ID.
  2832  * @param bool $force_delete Whether to bypass trash and force deletion
  3804  * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
  2833  * @return mixed False on failure. Post data on success.
  3805  * @return mixed False on failure. Post data on success.
  2834  */
  3806  */
  2835 function wp_delete_attachment( $post_id, $force_delete = false ) {
  3807 function wp_delete_attachment( $post_id, $force_delete = false ) {
  2836 	global $wpdb;
  3808 	global $wpdb;
  2837 
  3809 
  2849 
  3821 
  2850 	$meta = wp_get_attachment_metadata( $post_id );
  3822 	$meta = wp_get_attachment_metadata( $post_id );
  2851 	$backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  3823 	$backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  2852 	$file = get_attached_file( $post_id );
  3824 	$file = get_attached_file( $post_id );
  2853 
  3825 
       
  3826 	$intermediate_sizes = array();
       
  3827 	foreach ( get_intermediate_image_sizes() as $size ) {
       
  3828 		if ( $intermediate = image_get_intermediate_size( $post_id, $size ) )
       
  3829 			$intermediate_sizes[] = $intermediate;
       
  3830 	}
       
  3831 
       
  3832 	if ( is_multisite() )
       
  3833 		delete_transient( 'dirsize_cache' );
       
  3834 
  2854 	do_action('delete_attachment', $post_id);
  3835 	do_action('delete_attachment', $post_id);
  2855 
  3836 
  2856 	wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
  3837 	wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
  2857 	wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
  3838 	wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
  2858 
  3839 
  2859 	$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND meta_value = %d", $post_id ));
  3840 	delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts.
  2860 
  3841 
  2861 	$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
  3842 	$comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
  2862 	if ( ! empty($comment_ids) ) {
  3843 	foreach ( $comment_ids as $comment_id )
  2863 		do_action( 'delete_comment', $comment_ids );
  3844 		wp_delete_comment( $comment_id, true );
  2864 		$in_comment_ids = "'" . implode("', '", $comment_ids) . "'";
       
  2865 		$wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_ID IN($in_comment_ids)" );
       
  2866 		do_action( 'deleted_comment', $comment_ids );
       
  2867 	}
       
  2868 
  3845 
  2869 	$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
  3846 	$post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
  2870 	if ( !empty($post_meta_ids) ) {
  3847 	foreach ( $post_meta_ids as $mid )
  2871 		do_action( 'delete_postmeta', $post_meta_ids );
  3848 		delete_metadata_by_mid( 'post', $mid );
  2872 		$in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
       
  2873 		$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_id IN($in_post_meta_ids)" );
       
  2874 		do_action( 'deleted_postmeta', $post_meta_ids );
       
  2875 	}
       
  2876 
  3849 
  2877 	do_action( 'delete_post', $post_id );
  3850 	do_action( 'delete_post', $post_id );
  2878 	$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $post_id ));
  3851 	$wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
  2879 	do_action( 'deleted_post', $post_id );
  3852 	do_action( 'deleted_post', $post_id );
  2880 
  3853 
  2881 	$uploadpath = wp_upload_dir();
  3854 	$uploadpath = wp_upload_dir();
  2882 
  3855 
  2883 	if ( ! empty($meta['thumb']) ) {
  3856 	if ( ! empty($meta['thumb']) ) {
  2888 			@ unlink( path_join($uploadpath['basedir'], $thumbfile) );
  3861 			@ unlink( path_join($uploadpath['basedir'], $thumbfile) );
  2889 		}
  3862 		}
  2890 	}
  3863 	}
  2891 
  3864 
  2892 	// remove intermediate and backup images if there are any
  3865 	// remove intermediate and backup images if there are any
  2893 	$sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
  3866 	foreach ( $intermediate_sizes as $intermediate ) {
  2894 	foreach ( $sizes as $size ) {
  3867 		$intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] );
  2895 		if ( $intermediate = image_get_intermediate_size($post_id, $size) ) {
  3868 		@ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
  2896 			$intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
       
  2897 			@ unlink( path_join($uploadpath['basedir'], $intermediate_file) );
       
  2898 		}
       
  2899 	}
  3869 	}
  2900 
  3870 
  2901 	if ( is_array($backup_sizes) ) {
  3871 	if ( is_array($backup_sizes) ) {
  2902 		foreach ( $backup_sizes as $size ) {
  3872 		foreach ( $backup_sizes as $size ) {
  2903 			$del_file = path_join( dirname($meta['file']), $size['file'] );
  3873 			$del_file = path_join( dirname($meta['file']), $size['file'] );
  2904 			$del_file = apply_filters('wp_delete_file', $del_file);
  3874 			$del_file = apply_filters('wp_delete_file', $del_file);
  2905             @ unlink( path_join($uploadpath['basedir'], $del_file) );
  3875 			@ unlink( path_join($uploadpath['basedir'], $del_file) );
  2906 		}
  3876 		}
  2907 	}
  3877 	}
  2908 
  3878 
  2909 	$file = apply_filters('wp_delete_file', $file);
  3879 	$file = apply_filters('wp_delete_file', $file);
  2910 
  3880 
  2911 	if ( ! empty($file) )
  3881 	if ( ! empty($file) )
  2912 		@ unlink($file);
  3882 		@ unlink($file);
  2913 
  3883 
  2914 	clean_post_cache($post_id);
  3884 	clean_post_cache( $post );
  2915 
  3885 
  2916 	return $post;
  3886 	return $post;
  2917 }
  3887 }
  2918 
  3888 
  2919 /**
  3889 /**
  2923  *
  3893  *
  2924  * @param int $post_id Attachment ID
  3894  * @param int $post_id Attachment ID
  2925  * @param bool $unfiltered Optional, default is false. If true, filters are not run.
  3895  * @param bool $unfiltered Optional, default is false. If true, filters are not run.
  2926  * @return string|bool Attachment meta field. False on failure.
  3896  * @return string|bool Attachment meta field. False on failure.
  2927  */
  3897  */
  2928 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
  3898 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
  2929 	$post_id = (int) $post_id;
  3899 	$post_id = (int) $post_id;
  2930 	if ( !$post =& get_post( $post_id ) )
  3900 	if ( !$post =& get_post( $post_id ) )
  2931 		return false;
  3901 		return false;
  2932 
  3902 
  2933 	$data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
  3903 	$data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
  2966  * @return string
  3936  * @return string
  2967  */
  3937  */
  2968 function wp_get_attachment_url( $post_id = 0 ) {
  3938 function wp_get_attachment_url( $post_id = 0 ) {
  2969 	$post_id = (int) $post_id;
  3939 	$post_id = (int) $post_id;
  2970 	if ( !$post =& get_post( $post_id ) )
  3940 	if ( !$post =& get_post( $post_id ) )
       
  3941 		return false;
       
  3942 
       
  3943 	if ( 'attachment' != $post->post_type )
  2971 		return false;
  3944 		return false;
  2972 
  3945 
  2973 	$url = '';
  3946 	$url = '';
  2974 	if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
  3947 	if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
  2975 		if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
  3948 		if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
  2980 			else
  3953 			else
  2981 				$url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
  3954 				$url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
  2982 		}
  3955 		}
  2983 	}
  3956 	}
  2984 
  3957 
  2985 	if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
  3958 	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.
  2986 		$url = get_the_guid( $post->ID );
  3959 		$url = get_the_guid( $post->ID );
  2987 
  3960 
  2988 	if ( 'attachment' != $post->post_type || empty($url) )
  3961 	$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
       
  3962 
       
  3963 	if ( empty( $url ) )
  2989 		return false;
  3964 		return false;
  2990 
  3965 
  2991 	return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
  3966 	return $url;
  2992 }
  3967 }
  2993 
  3968 
  2994 /**
  3969 /**
  2995  * Retrieve thumbnail for an attachment.
  3970  * Retrieve thumbnail for an attachment.
  2996  *
  3971  *
  3068 /**
  4043 /**
  3069  * Retrieve the icon for a MIME type.
  4044  * Retrieve the icon for a MIME type.
  3070  *
  4045  *
  3071  * @since 2.1.0
  4046  * @since 2.1.0
  3072  *
  4047  *
  3073  * @param string $mime MIME type
  4048  * @param string|int $mime MIME type or attachment ID.
  3074  * @return string|bool
  4049  * @return string|bool
  3075  */
  4050  */
  3076 function wp_mime_type_icon( $mime = 0 ) {
  4051 function wp_mime_type_icon( $mime = 0 ) {
  3077 	if ( !is_numeric($mime) )
  4052 	if ( !is_numeric($mime) )
  3078 		$icon = wp_cache_get("mime_type_icon_$mime");
  4053 		$icon = wp_cache_get("mime_type_icon_$mime");
  3103 			$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  4078 			$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  3104 			$icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
  4079 			$icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
  3105 			$dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
  4080 			$dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
  3106 			$icon_files = array();
  4081 			$icon_files = array();
  3107 			while ( $dirs ) {
  4082 			while ( $dirs ) {
  3108 				$dir = array_shift($keys = array_keys($dirs));
  4083 				$keys = array_keys( $dirs );
       
  4084 				$dir = array_shift( $keys );
  3109 				$uri = array_shift($dirs);
  4085 				$uri = array_shift($dirs);
  3110 				if ( $dh = opendir($dir) ) {
  4086 				if ( $dh = opendir($dir) ) {
  3111 					while ( false !== $file = readdir($dh) ) {
  4087 					while ( false !== $file = readdir($dh) ) {
  3112 						$file = basename($file);
  4088 						$file = basename($file);
  3113 						if ( substr($file, 0, 1) == '.' )
  4089 						if ( substr($file, 0, 1) == '.' )
  3150 
  4126 
  3151 	return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
  4127 	return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
  3152 }
  4128 }
  3153 
  4129 
  3154 /**
  4130 /**
  3155  * Checked for changed slugs for published posts and save old slug.
  4131  * Checked for changed slugs for published post objects and save the old slug.
  3156  *
  4132  *
  3157  * The function is used along with form POST data. It checks for the wp-old-slug
  4133  * The function is used when a post object of any type is updated,
  3158  * POST field. Will only be concerned with published posts and the slug actually
  4134  * by comparing the current and previous post objects.
  3159  * changing.
       
  3160  *
  4135  *
  3161  * If the slug was changed and not already part of the old slugs then it will be
  4136  * If the slug was changed and not already part of the old slugs then it will be
  3162  * added to the post meta field ('_wp_old_slug') for storing old slugs for that
  4137  * added to the post meta field ('_wp_old_slug') for storing old slugs for that
  3163  * post.
  4138  * post.
  3164  *
  4139  *
  3165  * The most logically usage of this function is redirecting changed posts, so
  4140  * The most logically usage of this function is redirecting changed post objects, so
  3166  * that those that linked to an changed post will be redirected to the new post.
  4141  * that those that linked to an changed post will be redirected to the new post.
  3167  *
  4142  *
  3168  * @since 2.1.0
  4143  * @since 2.1.0
  3169  *
  4144  *
  3170  * @param int $post_id Post ID.
  4145  * @param int $post_id Post ID.
       
  4146  * @param object $post The Post Object
       
  4147  * @param object $post_before The Previous Post Object
  3171  * @return int Same as $post_id
  4148  * @return int Same as $post_id
  3172  */
  4149  */
  3173 function wp_check_for_changed_slugs($post_id) {
  4150 function wp_check_for_changed_slugs($post_id, $post, $post_before) {
  3174 	if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
  4151 	// dont bother if it hasnt changed
  3175 		return $post_id;
  4152 	if ( $post->post_name == $post_before->post_name )
  3176 
  4153 		return;
  3177 	$post = &get_post($post_id);
  4154 
  3178 
  4155 	// we're only concerned with published, non-hierarchical objects
  3179 	// we're only concerned with published posts
  4156 	if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) )
  3180 	if ( $post->post_status != 'publish' || $post->post_type != 'post' )
  4157 		return;
  3181 		return $post_id;
       
  3182 
       
  3183 	// only bother if the slug has changed
       
  3184 	if ( $post->post_name == $_POST['wp-old-slug'] )
       
  3185 		return $post_id;
       
  3186 
  4158 
  3187 	$old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
  4159 	$old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
  3188 
  4160 
  3189 	// if we haven't added this old slug before, add it now
  4161 	// if we haven't added this old slug before, add it now
  3190 	if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
  4162 	if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) )
  3191 		add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
  4163 		add_post_meta($post_id, '_wp_old_slug', $post_before->post_name);
  3192 
  4164 
  3193 	// if the new slug was used previously, delete it from the list
  4165 	// if the new slug was used previously, delete it from the list
  3194 	if ( in_array($post->post_name, $old_slugs) )
  4166 	if ( in_array($post->post_name, $old_slugs) )
  3195 		delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
  4167 		delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
  3196 
       
  3197 	return $post_id;
       
  3198 }
  4168 }
  3199 
  4169 
  3200 /**
  4170 /**
  3201  * Retrieve the private post SQL based on capability.
  4171  * Retrieve the private post SQL based on capability.
  3202  *
  4172  *
  3203  * This function provides a standardized way to appropriately select on the
  4173  * This function provides a standardized way to appropriately select on the
  3204  * post_status of posts/pages. The function will return a piece of SQL code that
  4174  * post_status of a post type. The function will return a piece of SQL code
  3205  * can be added to a WHERE clause; this SQL is constructed to allow all
  4175  * that can be added to a WHERE clause; this SQL is constructed to allow all
  3206  * published posts, and all private posts to which the user has access.
  4176  * published posts, and all private posts to which the user has access.
  3207  *
  4177  *
  3208  * It also allows plugins that define their own post type to control the cap by
       
  3209  * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
       
  3210  * the capability the user must have to read the private post type.
       
  3211  *
       
  3212  * @since 2.2.0
  4178  * @since 2.2.0
  3213  *
  4179  *
  3214  * @uses $user_ID
  4180  * @uses $user_ID
  3215  * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
       
  3216  *
  4181  *
  3217  * @param string $post_type currently only supports 'post' or 'page'.
  4182  * @param string $post_type currently only supports 'post' or 'page'.
  3218  * @return string SQL code that can be added to a where clause.
  4183  * @return string SQL code that can be added to a where clause.
  3219  */
  4184  */
  3220 function get_private_posts_cap_sql($post_type) {
  4185 function get_private_posts_cap_sql( $post_type ) {
  3221 	global $user_ID;
  4186 	return get_posts_by_author_sql( $post_type, false );
  3222 	$cap = '';
  4187 }
       
  4188 
       
  4189 /**
       
  4190  * Retrieve the post SQL based on capability, author, and type.
       
  4191  *
       
  4192  * @see get_private_posts_cap_sql() for full description.
       
  4193  *
       
  4194  * @since 3.0.0
       
  4195  * @param string $post_type Post type.
       
  4196  * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term.
       
  4197  * @param int $post_author Optional. Query posts having a single author ID.
       
  4198  * @return string SQL WHERE code that can be added to a query.
       
  4199  */
       
  4200 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null ) {
       
  4201 	global $user_ID, $wpdb;
  3223 
  4202 
  3224 	// Private posts
  4203 	// Private posts
  3225 	if ($post_type == 'post') {
  4204 	$post_type_obj = get_post_type_object( $post_type );
  3226 		$cap = 'read_private_posts';
  4205 	if ( ! $post_type_obj )
  3227 	// Private pages
  4206 		return $full ? 'WHERE 1 = 0' : ' 1 = 0 ';
  3228 	} elseif ($post_type == 'page') {
  4207 
  3229 		$cap = 'read_private_pages';
  4208 	// This hook is deprecated. Why you'd want to use it, I dunno.
  3230 	// Dunno what it is, maybe plugins have their own post type?
  4209 	if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) )
       
  4210 		$cap = $post_type_obj->cap->read_private_posts;
       
  4211 
       
  4212 	if ( $full ) {
       
  4213 		if ( null === $post_author ) {
       
  4214 			$sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type );
       
  4215 		} else {
       
  4216 			$sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type );
       
  4217 		}
  3231 	} else {
  4218 	} else {
  3232 		$cap = apply_filters('pub_priv_sql_capability', $cap);
  4219 		$sql = '';
  3233 
  4220 	}
  3234 		if (empty($cap)) {
  4221 
  3235 			// We don't know what it is, filters don't change anything,
  4222 	$sql .= "(post_status = 'publish'";
  3236 			// so set the SQL up to return nothing.
  4223 
  3237 			return '1 = 0';
  4224 	if ( current_user_can( $cap ) ) {
  3238 		}
       
  3239 	}
       
  3240 
       
  3241 	$sql = '(post_status = \'publish\'';
       
  3242 
       
  3243 	if (current_user_can($cap)) {
       
  3244 		// Does the user have the capability to view private posts? Guess so.
  4225 		// Does the user have the capability to view private posts? Guess so.
  3245 		$sql .= ' OR post_status = \'private\'';
  4226 		$sql .= " OR post_status = 'private'";
  3246 	} elseif (is_user_logged_in()) {
  4227 	} elseif ( is_user_logged_in() ) {
  3247 		// Users can view their own private posts.
  4228 		// Users can view their own private posts.
  3248 		$sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
  4229 		$id = (int) $user_ID;
  3249 	}
  4230 		if ( null === $post_author || ! $full ) {
       
  4231 			$sql .= " OR post_status = 'private' AND post_author = $id";
       
  4232 		} elseif ( $id == (int) $post_author ) {
       
  4233 			$sql .= " OR post_status = 'private'";
       
  4234 		} // else none
       
  4235 	} // else none
  3250 
  4236 
  3251 	$sql .= ')';
  4237 	$sql .= ')';
  3252 
  4238 
  3253 	return $sql;
  4239 	return $sql;
  3254 }
  4240 }
  3255 
  4241 
  3256 /**
  4242 /**
  3257  * Retrieve the date the the last post was published.
  4243  * Retrieve the date that the last post was published.
  3258  *
  4244  *
  3259  * The server timezone is the default and is the difference between GMT and
  4245  * The server timezone is the default and is the difference between GMT and
  3260  * server time. The 'blog' value is the date when the last post was posted. The
  4246  * server time. The 'blog' value is the date when the last post was posted. The
  3261  * 'gmt' is when the last post was posted in GMT formatted date.
  4247  * 'gmt' is when the last post was posted in GMT formatted date.
  3262  *
  4248  *
  3263  * @since 0.71
  4249  * @since 0.71
  3264  *
  4250  *
  3265  * @uses $wpdb
       
  3266  * @uses $blog_id
       
  3267  * @uses apply_filters() Calls 'get_lastpostdate' filter
  4251  * @uses apply_filters() Calls 'get_lastpostdate' filter
  3268  *
       
  3269  * @global mixed $cache_lastpostdate Stores the last post date
       
  3270  * @global mixed $pagenow The current page being viewed
       
  3271  *
  4252  *
  3272  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  4253  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  3273  * @return string The date of the last post.
  4254  * @return string The date of the last post.
  3274  */
  4255  */
  3275 function get_lastpostdate($timezone = 'server') {
  4256 function get_lastpostdate($timezone = 'server') {
  3276 	global $cache_lastpostdate, $wpdb, $blog_id;
  4257 	return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone );
  3277 	$add_seconds_server = date('Z');
       
  3278 	if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
       
  3279 		switch(strtolower($timezone)) {
       
  3280 			case 'gmt':
       
  3281 				$lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
       
  3282 				break;
       
  3283 			case 'blog':
       
  3284 				$lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
       
  3285 				break;
       
  3286 			case 'server':
       
  3287 				$lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
       
  3288 				break;
       
  3289 		}
       
  3290 		$cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
       
  3291 	} else {
       
  3292 		$lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
       
  3293 	}
       
  3294 	return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
       
  3295 }
  4258 }
  3296 
  4259 
  3297 /**
  4260 /**
  3298  * Retrieve last post modified date depending on timezone.
  4261  * Retrieve last post modified date depending on timezone.
  3299  *
  4262  *
  3300  * The server timezone is the default and is the difference between GMT and
  4263  * The server timezone is the default and is the difference between GMT and
  3301  * server time. The 'blog' value is just when the last post was modified. The
  4264  * server time. The 'blog' value is just when the last post was modified. The
  3302  * 'gmt' is when the last post was modified in GMT time.
  4265  * 'gmt' is when the last post was modified in GMT time.
  3303  *
  4266  *
  3304  * @since 1.2.0
  4267  * @since 1.2.0
  3305  * @uses $wpdb
       
  3306  * @uses $blog_id
       
  3307  * @uses apply_filters() Calls 'get_lastpostmodified' filter
  4268  * @uses apply_filters() Calls 'get_lastpostmodified' filter
  3308  *
       
  3309  * @global mixed $cache_lastpostmodified Stores the date the last post was modified
       
  3310  *
  4269  *
  3311  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  4270  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
  3312  * @return string The date the post was last modified.
  4271  * @return string The date the post was last modified.
  3313  */
  4272  */
  3314 function get_lastpostmodified($timezone = 'server') {
  4273 function get_lastpostmodified($timezone = 'server') {
  3315 	global $cache_lastpostmodified, $wpdb, $blog_id;
  4274 	$lastpostmodified = _get_last_post_time( $timezone, 'modified' );
  3316 	$add_seconds_server = date('Z');
  4275 
  3317 	if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
  4276 	$lastpostdate = get_lastpostdate($timezone);
  3318 		switch(strtolower($timezone)) {
  4277 	if ( $lastpostdate > $lastpostmodified )
       
  4278 		$lastpostmodified = $lastpostdate;
       
  4279 
       
  4280 	return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
       
  4281 }
       
  4282 
       
  4283 /**
       
  4284  * Retrieve latest post date data based on timezone.
       
  4285  *
       
  4286  * @access private
       
  4287  * @since 3.1.0
       
  4288  *
       
  4289  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
       
  4290  * @param string $field Field to check. Can be 'date' or 'modified'.
       
  4291  * @return string The date.
       
  4292  */
       
  4293 function _get_last_post_time( $timezone, $field ) {
       
  4294 	global $wpdb;
       
  4295 
       
  4296 	if ( !in_array( $field, array( 'date', 'modified' ) ) )
       
  4297 		return false;
       
  4298 
       
  4299 	$timezone = strtolower( $timezone );
       
  4300 
       
  4301 	$key = "lastpost{$field}:$timezone";
       
  4302 
       
  4303 	$date = wp_cache_get( $key, 'timeinfo' );
       
  4304 
       
  4305 	if ( !$date ) {
       
  4306 		$add_seconds_server = date('Z');
       
  4307 
       
  4308 		$post_types = get_post_types( array( 'public' => true ) );
       
  4309 		array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) );
       
  4310 		$post_types = "'" . implode( "', '", $post_types ) . "'";
       
  4311 
       
  4312 		switch ( $timezone ) {
  3319 			case 'gmt':
  4313 			case 'gmt':
  3320 				$lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
  4314 				$date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3321 				break;
  4315 				break;
  3322 			case 'blog':
  4316 			case 'blog':
  3323 				$lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
  4317 				$date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3324 				break;
  4318 				break;
  3325 			case 'server':
  4319 			case 'server':
  3326 				$lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
  4320 				$date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
  3327 				break;
  4321 				break;
  3328 		}
  4322 		}
  3329 		$lastpostdate = get_lastpostdate($timezone);
  4323 
  3330 		if ( $lastpostdate > $lastpostmodified ) {
  4324 		if ( $date )
  3331 			$lastpostmodified = $lastpostdate;
  4325 			wp_cache_set( $key, $date, 'timeinfo' );
  3332 		}
  4326 	}
  3333 		$cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
  4327 
  3334 	} else {
  4328 	return $date;
  3335 		$lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
       
  3336 	}
       
  3337 	return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
       
  3338 }
  4329 }
  3339 
  4330 
  3340 /**
  4331 /**
  3341  * Updates posts in cache.
  4332  * Updates posts in cache.
  3342  *
       
  3343  * @usedby update_page_cache() Aliased by this function.
       
  3344  *
  4333  *
  3345  * @package WordPress
  4334  * @package WordPress
  3346  * @subpackage Cache
  4335  * @subpackage Cache
  3347  * @since 1.5.1
  4336  * @since 1.5.1
  3348  *
  4337  *
  3349  * @param array $posts Array of post objects
  4338  * @param array $posts Array of post objects
  3350  */
  4339  */
  3351 function update_post_cache(&$posts) {
  4340 function update_post_cache( &$posts ) {
  3352 	if ( !$posts )
  4341 	if ( ! $posts )
  3353 		return;
  4342 		return;
  3354 
  4343 
  3355 	foreach ( $posts as $post )
  4344 	foreach ( $posts as $post )
  3356 		wp_cache_add($post->ID, $post, 'posts');
  4345 		wp_cache_add( $post->ID, $post, 'posts' );
  3357 }
  4346 }
  3358 
  4347 
  3359 /**
  4348 /**
  3360  * Will clean the post in the cache.
  4349  * Will clean the post in the cache.
  3361  *
  4350  *
  3371  * @subpackage Cache
  4360  * @subpackage Cache
  3372  * @since 2.0.0
  4361  * @since 2.0.0
  3373  *
  4362  *
  3374  * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
  4363  * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
  3375  *
  4364  *
  3376  * @param int $id The Post ID in the cache to clean
  4365  * @param object|int $post The post object or ID to remove from the cache
  3377  */
  4366  */
  3378 function clean_post_cache($id) {
  4367 function clean_post_cache( $post ) {
  3379 	global $_wp_suspend_cache_invalidation, $wpdb;
  4368 	global $_wp_suspend_cache_invalidation, $wpdb;
  3380 
  4369 
  3381 	if ( !empty($_wp_suspend_cache_invalidation) )
  4370 	if ( ! empty( $_wp_suspend_cache_invalidation ) )
  3382 		return;
  4371 		return;
  3383 
  4372 
  3384 	$id = (int) $id;
  4373 	$post = get_post( $post );
  3385 
  4374 	if ( empty( $post ) )
  3386 	wp_cache_delete($id, 'posts');
  4375 		return;
  3387 	wp_cache_delete($id, 'post_meta');
  4376 
  3388 
  4377 	wp_cache_delete( $post->ID, 'posts' );
  3389 	clean_object_term_cache($id, 'post');
  4378 	wp_cache_delete( $post->ID, 'post_meta' );
       
  4379 
       
  4380 	clean_object_term_cache( $post->ID, $post->post_type );
  3390 
  4381 
  3391 	wp_cache_delete( 'wp_get_archives', 'general' );
  4382 	wp_cache_delete( 'wp_get_archives', 'general' );
  3392 
  4383 
  3393 	do_action('clean_post_cache', $id);
  4384 	do_action( 'clean_post_cache', $post->ID, $post );
  3394 
  4385 
  3395 	if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
  4386 	if ( 'page' == $post->post_type ) {
  3396 		foreach( $children as $cid )
  4387 		wp_cache_delete( 'all_page_ids', 'posts' );
  3397 			clean_post_cache( $cid );
  4388 		wp_cache_delete( 'get_pages', 'posts' );
  3398 	}
  4389 		do_action( 'clean_page_cache', $post->ID );
  3399 }
  4390 	}
  3400 
  4391 
  3401 /**
  4392 	if ( $children = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_type FROM $wpdb->posts WHERE post_parent = %d", $post->ID) ) ) {
  3402  * Alias of update_post_cache().
  4393 		foreach ( $children as $child ) {
  3403  *
  4394 			// Loop detection
  3404  * @see update_post_cache() Posts and pages are the same, alias is intentional
  4395 			if ( $child->ID == $post->ID )
  3405  *
  4396 				continue;
  3406  * @package WordPress
  4397 			clean_post_cache( $child );
  3407  * @subpackage Cache
  4398 		}
  3408  * @since 1.5.1
  4399 	}
  3409  *
  4400 
  3410  * @param array $pages list of page objects
  4401 	if ( is_multisite() )
  3411  */
  4402 		wp_cache_delete( $wpdb->blogid . '-' . $post->ID, 'global-posts' );
  3412 function update_page_cache(&$pages) {
       
  3413 	update_post_cache($pages);
       
  3414 }
       
  3415 
       
  3416 /**
       
  3417  * Will clean the page in the cache.
       
  3418  *
       
  3419  * Clean (read: delete) page from cache that matches $id. Will also clean cache
       
  3420  * associated with 'all_page_ids' and 'get_pages'.
       
  3421  *
       
  3422  * @package WordPress
       
  3423  * @subpackage Cache
       
  3424  * @since 2.0.0
       
  3425  *
       
  3426  * @uses do_action() Will call the 'clean_page_cache' hook action.
       
  3427  *
       
  3428  * @param int $id Page ID to clean
       
  3429  */
       
  3430 function clean_page_cache($id) {
       
  3431 	clean_post_cache($id);
       
  3432 
       
  3433 	wp_cache_delete( 'all_page_ids', 'posts' );
       
  3434 	wp_cache_delete( 'get_pages', 'posts' );
       
  3435 
       
  3436 	do_action('clean_page_cache', $id);
       
  3437 }
  4403 }
  3438 
  4404 
  3439 /**
  4405 /**
  3440  * Call major cache updating functions for list of Post objects.
  4406  * Call major cache updating functions for list of Post objects.
  3441  *
  4407  *
  3447  * @uses update_post_cache()
  4413  * @uses update_post_cache()
  3448  * @uses update_object_term_cache()
  4414  * @uses update_object_term_cache()
  3449  * @uses update_postmeta_cache()
  4415  * @uses update_postmeta_cache()
  3450  *
  4416  *
  3451  * @param array $posts Array of Post objects
  4417  * @param array $posts Array of Post objects
  3452  */
  4418  * @param string $post_type The post type of the posts in $posts. Default is 'post'.
  3453 function update_post_caches(&$posts) {
  4419  * @param bool $update_term_cache Whether to update the term cache. Default is true.
       
  4420  * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
       
  4421  */
       
  4422 function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) {
  3454 	// No point in doing all this work if we didn't match any posts.
  4423 	// No point in doing all this work if we didn't match any posts.
  3455 	if ( !$posts )
  4424 	if ( !$posts )
  3456 		return;
  4425 		return;
  3457 
  4426 
  3458 	update_post_cache($posts);
  4427 	update_post_cache($posts);
  3459 
  4428 
  3460 	$post_ids = array();
  4429 	$post_ids = array();
  3461 
  4430 	foreach ( $posts as $post )
  3462 	for ($i = 0; $i < count($posts); $i++)
  4431 		$post_ids[] = $post->ID;
  3463 		$post_ids[] = $posts[$i]->ID;
  4432 
  3464 
  4433 	if ( empty($post_type) )
  3465 	update_object_term_cache($post_ids, 'post');
  4434 		$post_type = 'post';
  3466 
  4435 
  3467 	update_postmeta_cache($post_ids);
  4436 	if ( $update_term_cache ) {
       
  4437 		if ( is_array($post_type) ) {
       
  4438 			$ptypes = $post_type;
       
  4439 		} elseif ( 'any' == $post_type ) {
       
  4440 			// Just use the post_types in the supplied posts.
       
  4441 			foreach ( $posts as $post )
       
  4442 				$ptypes[] = $post->post_type;
       
  4443 			$ptypes = array_unique($ptypes);
       
  4444 		} else {
       
  4445 			$ptypes = array($post_type);
       
  4446 		}
       
  4447 
       
  4448 		if ( ! empty($ptypes) )
       
  4449 			update_object_term_cache($post_ids, $ptypes);
       
  4450 	}
       
  4451 
       
  4452 	if ( $update_meta_cache )
       
  4453 		update_postmeta_cache($post_ids);
  3468 }
  4454 }
  3469 
  4455 
  3470 /**
  4456 /**
  3471  * Updates metadata cache for list of post IDs.
  4457  * Updates metadata cache for list of post IDs.
  3472  *
  4458  *
  3483  * @param array $post_ids List of post IDs.
  4469  * @param array $post_ids List of post IDs.
  3484  * @return bool|array Returns false if there is nothing to update or an array of metadata.
  4470  * @return bool|array Returns false if there is nothing to update or an array of metadata.
  3485  */
  4471  */
  3486 function update_postmeta_cache($post_ids) {
  4472 function update_postmeta_cache($post_ids) {
  3487 	return update_meta_cache('post', $post_ids);
  4473 	return update_meta_cache('post', $post_ids);
       
  4474 }
       
  4475 
       
  4476 /**
       
  4477  * Will clean the attachment in the cache.
       
  4478  *
       
  4479  * Cleaning means delete from the cache. Optionally will clean the term
       
  4480  * object cache associated with the attachment ID.
       
  4481  *
       
  4482  * This function will not run if $_wp_suspend_cache_invalidation is not empty. See
       
  4483  * wp_suspend_cache_invalidation().
       
  4484  *
       
  4485  * @package WordPress
       
  4486  * @subpackage Cache
       
  4487  * @since 3.0.0
       
  4488  *
       
  4489  * @uses do_action() Calls 'clean_attachment_cache' on $id.
       
  4490  *
       
  4491  * @param int $id The attachment ID in the cache to clean
       
  4492  * @param bool $clean_terms optional. Whether to clean terms cache
       
  4493  */
       
  4494 function clean_attachment_cache($id, $clean_terms = false) {
       
  4495 	global $_wp_suspend_cache_invalidation;
       
  4496 
       
  4497 	if ( !empty($_wp_suspend_cache_invalidation) )
       
  4498 		return;
       
  4499 
       
  4500 	$id = (int) $id;
       
  4501 
       
  4502 	wp_cache_delete($id, 'posts');
       
  4503 	wp_cache_delete($id, 'post_meta');
       
  4504 
       
  4505 	if ( $clean_terms )
       
  4506 		clean_object_term_cache($id, 'attachment');
       
  4507 
       
  4508 	do_action('clean_attachment_cache', $id);
  3488 }
  4509 }
  3489 
  4510 
  3490 //
  4511 //
  3491 // Hooks
  4512 // Hooks
  3492 //
  4513 //
  3512 		if ( '' == get_the_guid($post->ID) )
  4533 		if ( '' == get_the_guid($post->ID) )
  3513 			$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
  4534 			$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
  3514 		do_action('private_to_published', $post->ID);  // Deprecated, use private_to_publish
  4535 		do_action('private_to_published', $post->ID);  // Deprecated, use private_to_publish
  3515 	}
  4536 	}
  3516 
  4537 
       
  4538 	// If published posts changed clear the lastpostmodified cache
       
  4539 	if ( 'publish' == $new_status || 'publish' == $old_status) {
       
  4540 		foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
       
  4541 			wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
       
  4542 			wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
       
  4543 		}
       
  4544 	}
       
  4545 
  3517 	// Always clears the hook in case the post status bounced from future to draft.
  4546 	// Always clears the hook in case the post status bounced from future to draft.
  3518 	wp_clear_scheduled_hook('publish_future_post', $post->ID);
  4547 	wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
  3519 }
  4548 }
  3520 
  4549 
  3521 /**
  4550 /**
  3522  * Hook used to schedule publication for a post marked for the future.
  4551  * Hook used to schedule publication for a post marked for the future.
  3523  *
  4552  *
  3524  * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
  4553  * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
  3525  *
  4554  *
  3526  * @since 2.3.0
  4555  * @since 2.3.0
  3527  * @access private
  4556  * @access private
  3528  *
  4557  *
  3529  * @param int $deprecated Not Used. Can be set to null.
  4558  * @param int $deprecated Not used. Can be set to null. Never implemented.
       
  4559  *   Not marked as deprecated with _deprecated_argument() as it conflicts with
       
  4560  *   wp_transition_post_status() and the default filter for _future_post_hook().
  3530  * @param object $post Object type containing the post information
  4561  * @param object $post Object type containing the post information
  3531  */
  4562  */
  3532 function _future_post_hook($deprecated = '', $post) {
  4563 function _future_post_hook( $deprecated = '', $post ) {
  3533 	wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
  4564 	wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
  3534 	wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
  4565 	wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
  3535 }
  4566 }
  3536 
  4567 
  3537 /**
  4568 /**
  3538  * Hook to schedule pings and enclosures when a post is published.
  4569  * Hook to schedule pings and enclosures when a post is published.
  3539  *
  4570  *
  3555 		do_action('app_publish_post', $post_id);
  4586 		do_action('app_publish_post', $post_id);
  3556 
  4587 
  3557 	if ( defined('WP_IMPORTING') )
  4588 	if ( defined('WP_IMPORTING') )
  3558 		return;
  4589 		return;
  3559 
  4590 
  3560 	$data = array( 'post_id' => $post_id, 'meta_value' => '1' );
  4591 	if ( get_option('default_pingback_flag') )
  3561 	if ( get_option('default_pingback_flag') ) {
  4592 		add_post_meta( $post_id, '_pingme', '1' );
  3562 		$wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
  4593 	add_post_meta( $post_id, '_encloseme', '1' );
  3563 		do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_pingme', 1 );
       
  3564 	}
       
  3565 	$wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
       
  3566 	do_action( 'added_postmeta', $wpdb->insert_id, $post_id, '_encloseme', 1 );
       
  3567 
  4594 
  3568 	wp_schedule_single_event(time(), 'do_pings');
  4595 	wp_schedule_single_event(time(), 'do_pings');
  3569 }
  4596 }
  3570 
  4597 
  3571 /**
  4598 /**
  3572  * Hook used to prevent page/post cache and rewrite rules from staying dirty.
  4599  * Hook used to prevent page/post cache from staying dirty when a post is saved.
  3573  *
       
  3574  * Does two things. If the post is a page and has a template then it will
       
  3575  * update/add that template to the meta. For both pages and posts, it will clean
       
  3576  * the post cache to make sure that the cache updates to the changes done
       
  3577  * recently. For pages, the rewrite rules of WordPress are flushed to allow for
       
  3578  * any changes.
       
  3579  *
       
  3580  * The $post parameter, only uses 'post_type' property and 'page_template'
       
  3581  * property.
       
  3582  *
  4600  *
  3583  * @since 2.3.0
  4601  * @since 2.3.0
  3584  * @access private
  4602  * @access private
  3585  * @uses $wp_rewrite Flushes Rewrite Rules.
       
  3586  *
  4603  *
  3587  * @param int $post_id The ID in the database table for the $post
  4604  * @param int $post_id The ID in the database table for the $post
  3588  * @param object $post Object type containing the post information
  4605  * @param object $post Object type containing the post information
  3589  */
  4606  */
  3590 function _save_post_hook($post_id, $post) {
  4607 function _save_post_hook( $post_id, $post ) {
  3591 	if ( $post->post_type == 'page' ) {
  4608 	clean_post_cache( $post );
  3592 		clean_page_cache($post_id);
       
  3593 		// Avoid flushing rules for every post during import.
       
  3594 		if ( !defined('WP_IMPORTING') ) {
       
  3595 			global $wp_rewrite;
       
  3596 			$wp_rewrite->flush_rules(false);
       
  3597 		}
       
  3598 	} else {
       
  3599 		clean_post_cache($post_id);
       
  3600 	}
       
  3601 }
  4609 }
  3602 
  4610 
  3603 /**
  4611 /**
  3604  * Retrieve post ancestors and append to post ancestors property.
  4612  * Retrieve post ancestors and append to post ancestors property.
  3605  *
  4613  *
  3610  * The parameter is passed by reference, so nothing needs to be returned. The
  4618  * The parameter is passed by reference, so nothing needs to be returned. The
  3611  * property will be updated and can be referenced after the function is
  4619  * property will be updated and can be referenced after the function is
  3612  * complete. The post parent will be an ancestor and the parent of the post
  4620  * complete. The post parent will be an ancestor and the parent of the post
  3613  * parent will be an ancestor. There will only be two ancestors at the most.
  4621  * parent will be an ancestor. There will only be two ancestors at the most.
  3614  *
  4622  *
  3615  * @since unknown
  4623  * @since 2.5.0
  3616  * @access private
  4624  * @access private
  3617  * @uses $wpdb
  4625  * @uses $wpdb
  3618  *
  4626  *
  3619  * @param object $_post Post data.
  4627  * @param object $_post Post data.
  3620  * @return null When nothing needs to be done.
  4628  * @return null When nothing needs to be done.
  3628 	$_post->ancestors = array();
  4636 	$_post->ancestors = array();
  3629 
  4637 
  3630 	if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
  4638 	if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
  3631 		return;
  4639 		return;
  3632 
  4640 
  3633 	$id = $_post->ancestors[] = $_post->post_parent;
  4641 	$id = $_post->ancestors[] = (int) $_post->post_parent;
  3634 	while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
  4642 	while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
  3635 		if ( $id == $ancestor )
  4643 		// Loop detection: If the ancestor has been seen before, break.
       
  4644 		if ( ( $ancestor == $_post->ID ) || in_array($ancestor,  $_post->ancestors) )
  3636 			break;
  4645 			break;
  3637 		$id = $_post->ancestors[] = $ancestor;
  4646 		$id = $_post->ancestors[] = (int) $ancestor;
  3638 	}
  4647 	}
  3639 }
  4648 }
  3640 
  4649 
  3641 /**
  4650 /**
  3642  * Determines which fields of posts are to be saved in revisions.
  4651  * Determines which fields of posts are to be saved in revisions.
  3643  *
  4652  *
  3644  * Does two things. If passed a post *array*, it will return a post array ready
  4653  * Does two things. If passed a post *array*, it will return a post array ready
  3645  * to be insterted into the posts table as a post revision. Otherwise, returns
  4654  * to be inserted into the posts table as a post revision. Otherwise, returns
  3646  * an array whose keys are the post fields to be saved for post revisions.
  4655  * an array whose keys are the post fields to be saved for post revisions.
  3647  *
  4656  *
  3648  * @package WordPress
  4657  * @package WordPress
  3649  * @subpackage Post_Revisions
  4658  * @subpackage Post_Revisions
  3650  * @since 2.6.0
  4659  * @since 2.6.0
  3709 	// We do autosaves manually with wp_create_post_autosave()
  4718 	// We do autosaves manually with wp_create_post_autosave()
  3710 	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
  4719 	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
  3711 		return;
  4720 		return;
  3712 
  4721 
  3713 	// WP_POST_REVISIONS = 0, false
  4722 	// WP_POST_REVISIONS = 0, false
  3714 	if ( !constant('WP_POST_REVISIONS') )
  4723 	if ( ! WP_POST_REVISIONS )
  3715 		return;
  4724 		return;
  3716 
  4725 
  3717 	if ( !$post = get_post( $post_id, ARRAY_A ) )
  4726 	if ( !$post = get_post( $post_id, ARRAY_A ) )
  3718 		return;
  4727 		return;
  3719 
  4728 
  3720 	if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
  4729 	if ( !post_type_supports($post['post_type'], 'revisions') )
  3721 		return;
  4730 		return;
  3722 
  4731 
  3723 	$return = _wp_put_post_revision( $post );
  4732 	$return = _wp_put_post_revision( $post );
  3724 
  4733 
  3725 	// WP_POST_REVISIONS = true (default), -1
  4734 	// WP_POST_REVISIONS = true (default), -1
  3727 		return $return;
  4736 		return $return;
  3728 
  4737 
  3729 	// all revisions and (possibly) one autosave
  4738 	// all revisions and (possibly) one autosave
  3730 	$revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
  4739 	$revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
  3731 
  4740 
  3732 	// WP_POST_REVISIONS = (int) (# of autasaves to save)
  4741 	// WP_POST_REVISIONS = (int) (# of autosaves to save)
  3733 	$delete = count($revisions) - WP_POST_REVISIONS;
  4742 	$delete = count($revisions) - WP_POST_REVISIONS;
  3734 
  4743 
  3735 	if ( $delete < 1 )
  4744 	if ( $delete < 1 )
  3736 		return $return;
  4745 		return $return;
  3737 
  4746 
  3876  *
  4885  *
  3877  * @uses get_post()
  4886  * @uses get_post()
  3878  *
  4887  *
  3879  * @param int|object $post Post ID or post object
  4888  * @param int|object $post Post ID or post object
  3880  * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
  4889  * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
  3881  * @param string $filter Optional sanitation filter.  @see sanitize_post()
  4890  * @param string $filter Optional sanitation filter. @see sanitize_post()
  3882  * @return mixed Null if error or post object if success
  4891  * @return mixed Null if error or post object if success
  3883  */
  4892  */
  3884 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
  4893 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
  3885 	$null = null;
  4894 	$null = null;
  3886 	if ( !$revision = get_post( $post, OBJECT, $filter ) )
  4895 	if ( !$revision = get_post( $post, OBJECT, $filter ) )
  3958  *
  4967  *
  3959  * @uses wp_get_post_revision()
  4968  * @uses wp_get_post_revision()
  3960  * @uses wp_delete_post()
  4969  * @uses wp_delete_post()
  3961  *
  4970  *
  3962  * @param int|object $revision_id Revision ID or revision object.
  4971  * @param int|object $revision_id Revision ID or revision object.
  3963  * @param array $fields Optional. What fields to restore from.  Defaults to all.
  4972  * @return mixed Null or WP_Error if error, deleted post if success.
  3964  * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
       
  3965  */
  4973  */
  3966 function wp_delete_post_revision( $revision_id ) {
  4974 function wp_delete_post_revision( $revision_id ) {
  3967 	if ( !$revision = wp_get_post_revision( $revision_id ) )
  4975 	if ( !$revision = wp_get_post_revision( $revision_id ) )
  3968 		return $revision;
  4976 		return $revision;
  3969 
  4977 
  3988  *
  4996  *
  3989  * @param int|object $post_id Post ID or post object
  4997  * @param int|object $post_id Post ID or post object
  3990  * @return array empty if no revisions
  4998  * @return array empty if no revisions
  3991  */
  4999  */
  3992 function wp_get_post_revisions( $post_id = 0, $args = null ) {
  5000 function wp_get_post_revisions( $post_id = 0, $args = null ) {
  3993 	if ( !constant('WP_POST_REVISIONS') )
  5001 	if ( ! WP_POST_REVISIONS )
  3994 		return array();
  5002 		return array();
  3995 	if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
  5003 	if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
  3996 		return array();
  5004 		return array();
  3997 
  5005 
  3998 	$defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
  5006 	$defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
  4032 			wp_die( __('You do not have permission to preview drafts.') );
  5040 			wp_die( __('You do not have permission to preview drafts.') );
  4033 
  5041 
  4034 		add_filter('the_preview', '_set_preview');
  5042 		add_filter('the_preview', '_set_preview');
  4035 	}
  5043 	}
  4036 }
  5044 }
       
  5045 
       
  5046 /**
       
  5047  * Returns the post's parent's post_ID
       
  5048  *
       
  5049  * @since 3.1.0
       
  5050  *
       
  5051  * @param int $post_id
       
  5052  *
       
  5053  * @return int|bool false on error
       
  5054  */
       
  5055 function wp_get_post_parent_id( $post_ID ) {
       
  5056 	$post = get_post( $post_ID );
       
  5057 	if ( !$post || is_wp_error( $post ) )
       
  5058 		return false;
       
  5059 	return (int) $post->post_parent;
       
  5060 }
       
  5061 
       
  5062 /**
       
  5063  * Checks the given subset of the post hierarchy for hierarchy loops.
       
  5064  * Prevents loops from forming and breaks those that it finds.
       
  5065  *
       
  5066  * Attached to the wp_insert_post_parent filter.
       
  5067  *
       
  5068  * @since 3.1.0
       
  5069  * @uses wp_find_hierarchy_loop()
       
  5070  *
       
  5071  * @param int $post_parent ID of the parent for the post we're checking.
       
  5072  * @param int $post_ID ID of the post we're checking.
       
  5073  *
       
  5074  * @return int The new post_parent for the post.
       
  5075  */
       
  5076 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
       
  5077 	// Nothing fancy here - bail
       
  5078 	if ( !$post_parent )
       
  5079 		return 0;
       
  5080 
       
  5081 	// New post can't cause a loop
       
  5082 	if ( empty( $post_ID ) )
       
  5083 		return $post_parent;
       
  5084 
       
  5085 	// Can't be its own parent
       
  5086 	if ( $post_parent == $post_ID )
       
  5087 		return 0;
       
  5088 
       
  5089 	// Now look for larger loops
       
  5090 
       
  5091 	if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
       
  5092 		return $post_parent; // No loop
       
  5093 
       
  5094 	// Setting $post_parent to the given value causes a loop
       
  5095 	if ( isset( $loop[$post_ID] ) )
       
  5096 		return 0;
       
  5097 
       
  5098 	// There's a loop, but it doesn't contain $post_ID. Break the loop.
       
  5099 	foreach ( array_keys( $loop ) as $loop_member )
       
  5100 		wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
       
  5101 
       
  5102 	return $post_parent;
       
  5103 }
       
  5104 
       
  5105 /**
       
  5106  * Returns an array of post format slugs to their translated and pretty display versions
       
  5107  *
       
  5108  * @since 3.1.0
       
  5109  *
       
  5110  * @return array The array of translations
       
  5111  */
       
  5112 function get_post_format_strings() {
       
  5113 	$strings = array(
       
  5114 		'standard' => _x( 'Standard', 'Post format' ), // Special case. any value that evals to false will be considered standard
       
  5115 		'aside'    => _x( 'Aside',    'Post format' ),
       
  5116 		'chat'     => _x( 'Chat',     'Post format' ),
       
  5117 		'gallery'  => _x( 'Gallery',  'Post format' ),
       
  5118 		'link'     => _x( 'Link',     'Post format' ),
       
  5119 		'image'    => _x( 'Image',    'Post format' ),
       
  5120 		'quote'    => _x( 'Quote',    'Post format' ),
       
  5121 		'status'   => _x( 'Status',   'Post format' ),
       
  5122 		'video'    => _x( 'Video',    'Post format' ),
       
  5123 		'audio'    => _x( 'Audio',    'Post format' ),
       
  5124 	);
       
  5125 	return $strings;
       
  5126 }
       
  5127 
       
  5128 /**
       
  5129  * Retrieves an array of post format slugs.
       
  5130  *
       
  5131  * @since 3.1.0
       
  5132  *
       
  5133  * @return array The array of post format slugs.
       
  5134  */
       
  5135 function get_post_format_slugs() {
       
  5136 	$slugs = array_keys( get_post_format_strings() );
       
  5137 	return array_combine( $slugs, $slugs );
       
  5138 }
       
  5139 
       
  5140 /**
       
  5141  * Returns a pretty, translated version of a post format slug
       
  5142  *
       
  5143  * @since 3.1.0
       
  5144  *
       
  5145  * @param string $slug A post format slug
       
  5146  * @return string The translated post format name
       
  5147  */
       
  5148 function get_post_format_string( $slug ) {
       
  5149 	$strings = get_post_format_strings();
       
  5150 	if ( !$slug )
       
  5151 		return $strings['standard'];
       
  5152 	else
       
  5153 		return ( isset( $strings[$slug] ) ) ? $strings[$slug] : '';
       
  5154 }
       
  5155 
       
  5156 /**
       
  5157  * Sets a post thumbnail.
       
  5158  *
       
  5159  * @since 3.1.0
       
  5160  *
       
  5161  * @param int|object $post Post ID or object where thumbnail should be attached.
       
  5162  * @param int $thumbnail_id Thumbnail to attach.
       
  5163  * @return bool True on success, false on failure.
       
  5164  */
       
  5165 function set_post_thumbnail( $post, $thumbnail_id ) {
       
  5166 	$post = get_post( $post );
       
  5167 	$thumbnail_id = absint( $thumbnail_id );
       
  5168 	if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
       
  5169 		$thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' );
       
  5170 		if ( ! empty( $thumbnail_html ) ) {
       
  5171 			return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
       
  5172 		}
       
  5173 	}
       
  5174 	return false;
       
  5175 }
       
  5176 
       
  5177 /**
       
  5178  * Removes a post thumbnail.
       
  5179  *
       
  5180  * @since 3.3.0
       
  5181  *
       
  5182  * @param int|object $post Post ID or object where thumbnail should be removed from.
       
  5183  * @return bool True on success, false on failure.
       
  5184  */
       
  5185 function delete_post_thumbnail( $post ) {
       
  5186 	$post = get_post( $post );
       
  5187 	if ( $post )
       
  5188 		return delete_post_meta( $post->ID, '_thumbnail_id' );
       
  5189 	return false;
       
  5190 }
       
  5191 
       
  5192 /**
       
  5193  * Returns a link to a post format index.
       
  5194  *
       
  5195  * @since 3.1.0
       
  5196  *
       
  5197  * @param string $format Post format
       
  5198  * @return string Link
       
  5199  */
       
  5200 function get_post_format_link( $format ) {
       
  5201 	$term = get_term_by('slug', 'post-format-' . $format, 'post_format' );
       
  5202 	if ( ! $term || is_wp_error( $term ) )
       
  5203 		return false;
       
  5204 	return get_term_link( $term );
       
  5205 }
       
  5206 
       
  5207 /**
       
  5208  * Deletes auto-drafts for new posts that are > 7 days old
       
  5209  *
       
  5210  * @since 3.4.0
       
  5211  */
       
  5212 function wp_delete_auto_drafts() {
       
  5213 	global $wpdb;
       
  5214 
       
  5215 	// Cleanup old auto-drafts more than 7 days old
       
  5216 	$old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
       
  5217 	foreach ( (array) $old_posts as $delete )
       
  5218 		wp_delete_post( $delete, true ); // Force delete
       
  5219 }
       
  5220 
       
  5221 /**
       
  5222  * Filters the request to allow for the format prefix.
       
  5223  *
       
  5224  * @access private
       
  5225  * @since 3.1.0
       
  5226  */
       
  5227 function _post_format_request( $qvs ) {
       
  5228 	if ( ! isset( $qvs['post_format'] ) )
       
  5229 		return $qvs;
       
  5230 	$slugs = get_post_format_slugs();
       
  5231 	if ( isset( $slugs[ $qvs['post_format'] ] ) )
       
  5232 		$qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ];
       
  5233 	$tax = get_taxonomy( 'post_format' );
       
  5234 	if ( ! is_admin() )
       
  5235 		$qvs['post_type'] = $tax->object_type;
       
  5236 	return $qvs;
       
  5237 }
       
  5238 add_filter( 'request', '_post_format_request' );
       
  5239 
       
  5240 /**
       
  5241  * Filters the post format term link to remove the format prefix.
       
  5242  *
       
  5243  * @access private
       
  5244  * @since 3.1.0
       
  5245  */
       
  5246 function _post_format_link( $link, $term, $taxonomy ) {
       
  5247 	global $wp_rewrite;
       
  5248 	if ( 'post_format' != $taxonomy )
       
  5249 		return $link;
       
  5250 	if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) {
       
  5251 		return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link );
       
  5252 	} else {
       
  5253 		$link = remove_query_arg( 'post_format', $link );
       
  5254 		return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link );
       
  5255 	}
       
  5256 }
       
  5257 add_filter( 'term_link', '_post_format_link', 10, 3 );
       
  5258 
       
  5259 /**
       
  5260  * Remove the post format prefix from the name property of the term object created by get_term().
       
  5261  *
       
  5262  * @access private
       
  5263  * @since 3.1.0
       
  5264  */
       
  5265 function _post_format_get_term( $term ) {
       
  5266 	if ( isset( $term->slug ) ) {
       
  5267 		$term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
       
  5268 	}
       
  5269 	return $term;
       
  5270 }
       
  5271 add_filter( 'get_post_format', '_post_format_get_term' );
       
  5272 
       
  5273 /**
       
  5274  * Remove the post format prefix from the name property of the term objects created by get_terms().
       
  5275  *
       
  5276  * @access private
       
  5277  * @since 3.1.0
       
  5278  */
       
  5279 function _post_format_get_terms( $terms, $taxonomies, $args ) {
       
  5280 	if ( in_array( 'post_format', (array) $taxonomies ) ) {
       
  5281 		if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) {
       
  5282 			foreach( $terms as $order => $name ) {
       
  5283 				$terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) );
       
  5284 			}
       
  5285 		} else {
       
  5286 			foreach ( (array) $terms as $order => $term ) {
       
  5287 				if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
       
  5288 					$terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
       
  5289 				}
       
  5290 			}
       
  5291 		}
       
  5292 	}
       
  5293 	return $terms;
       
  5294 }
       
  5295 add_filter( 'get_terms', '_post_format_get_terms', 10, 3 );
       
  5296 
       
  5297 /**
       
  5298  * Remove the post format prefix from the name property of the term objects created by wp_get_object_terms().
       
  5299  *
       
  5300  * @access private
       
  5301  * @since 3.1.0
       
  5302  */
       
  5303 function _post_format_wp_get_object_terms( $terms ) {
       
  5304 	foreach ( (array) $terms as $order => $term ) {
       
  5305 		if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) {
       
  5306 			$terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) );
       
  5307 		}
       
  5308 	}
       
  5309 	return $terms;
       
  5310 }
       
  5311 add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' );
       
  5312 
       
  5313 /**
       
  5314  * 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.
       
  5315  *
       
  5316  * @access private
       
  5317  * @param string $new_status
       
  5318  * @param string $old_status
       
  5319  * @param object $post
       
  5320  * @since 3.3.0
       
  5321  */
       
  5322 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
       
  5323 	// Update counts for the post's terms.
       
  5324 	foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
       
  5325 		$tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
       
  5326 		wp_update_term_count( $tt_ids, $taxonomy );
       
  5327 	}
       
  5328 }
       
  5329 
       
  5330 /**
       
  5331  * Adds any posts from the given ids to the cache that do not already exist in cache
       
  5332  *
       
  5333  * @since 3.4.0
       
  5334  *
       
  5335  * @access private
       
  5336  *
       
  5337  * @param array $post_ids ID list
       
  5338  * @param bool $update_term_cache Whether to update the term cache. Default is true.
       
  5339  * @param bool $update_meta_cache Whether to update the meta cache. Default is true.
       
  5340  */
       
  5341 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
       
  5342 	global $wpdb;
       
  5343 
       
  5344 	$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
       
  5345 	if ( !empty( $non_cached_ids ) ) {
       
  5346 		$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
       
  5347 
       
  5348 		update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
       
  5349 	}
       
  5350 }