set_post_type()WP 2.5.0

Update the post type for the post ID.

The page or post cache will be cleaned for the post ID.

No Hooks.

Return

Int|false. Amount of rows changed. Should be 1 for success and 0 for failure.

Usage

set_post_type( $post_id, $post_type );
$post_id(int)
Post ID to change post type.
$post_type(string)
Post type. Accepts 'post' or 'page' to name a few.
Default: 'post'

Examples

0

#1 Update the type of posts

Suppose we have a post with ID 15. Let's turn it into a permanent page by changing the post type to page:

$post_id = 15;
if ( set_post_type( $post_id, 'page' ) ) {
	  echo "Post 15 now page";
}
else {
	  echo "Unable to change the post type to page";
}

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 2.5.0 Introduced.

set_post_type() code WP 6.8

function set_post_type( $post_id = 0, $post_type = 'post' ) {
	global $wpdb;

	$post_type = sanitize_post_field( 'post_type', $post_type, $post_id, 'db' );
	$return    = $wpdb->update( $wpdb->posts, array( 'post_type' => $post_type ), array( 'ID' => $post_id ) );

	clean_post_cache( $post_id );

	return $return;
}