set_post_type( int $post_id, string $post_type = ‘post’ ): int|false

Updates the post type for the post ID.

Description

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

Parameters

$post_idintoptional
Post ID to change post type. Default 0.
$post_typestringoptional
Post type. Accepts 'post' or 'page' to name a few. Default 'post'.

Default:'post'

Return

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

Source

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;
}

Changelog

VersionDescription
2.5.0Introduced.

User Contributed Notes

  1. Skip to note 4 content
    • Move or assign any post into specific post type
    • After successfully assign to post type post data will remain same in the post like post title, post content
    • Works with custom post types
    $post_id = 123; //your post id
    $post_type = 'page'; //your post type name also you can use custom post type
    
    if ( set_post_type( $post_id, $post_type  ) ) {
      printf( __( 'Post %d is now a %s', 'textdomain' ), $post_id, $post_type );
    } else {
       printf( __( 'Impossible to transform this post into a %s', 'textdomain' ), $post_type );
    }

You must log in before being able to contribute a note or feedback.