set_post_type()
Updates the post type for the specified post (record). For example: post >> page.
The function changes the post_type field in the wp_posts table to the specified type and clears the post cache so that the changes take effect.
The cache of the post and its associated taxonomies and terms will be cleared.
No Hooks.
Returns
Int|false.
int- the number of rows affected in the DB after the update (usually 1). The result of the $wpdb->update() query.false- an error occurred during the query.
Usage
set_post_type( $post_id, $post_type );
- $post_id(integer)
- ID of the post whose type needs to be changed.
Default: 0 - $post_type(string)
- The name of the post type to set. The name of the new post type.
Default: 'post'
Examples
#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.
$wpdbWordPress database abstraction object.
Changelog
| Since 2.5.0 | Introduced. |
set_post_type() set post type code WP 6.9.1
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;
}