Change a Post's Type From the Editor
Adds a "Post type" box to the editor sidebar for administrators that converts an item into another post type, such as turning a post into a page, keeping its content and URL slug.
Opens WPIDE on
Code
add_action( 'add_meta_boxes', function ( $post_type, $post ) {
if ( ! current_user_can( 'manage_options' ) || ! $post instanceof WP_Post ) {
return;
}
add_meta_box( 'wpide-change-type', 'Post type', function ( $post ) {
$types = get_post_types( array( 'public' => true, 'show_ui' => true ), 'objects' );
wp_nonce_field( 'wpide_change_type_' . $post->ID, 'wpide_post_type_nonce' );
echo '<label class="screen-reader-text" for="wpide-new-post-type">Post type</label><select name="wpide_new_post_type" id="wpide-new-post-type" style="width:100%">';
foreach ( $types as $type ) {
if ( 'attachment' === $type->name ) {
continue;
}
printf( '<option value="%s"%s>%s</option>', esc_attr( $type->name ), selected( $post->post_type, $type->name, false ), esc_html( $type->labels->singular_name ) );
}
echo '</select><p class="description">Changes apply when you save.</p>';
}, null, 'side', 'low' );
}, 10, 2 );
add_action( 'save_post', function ( $post_id, $post ) {
if ( ! isset( $_POST['wpide_post_type_nonce'], $_POST['wpide_new_post_type'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_post_type_nonce'] ), 'wpide_change_type_' . $post_id ) ) {
return;
}
if ( ! current_user_can( 'manage_options' ) || wp_is_post_revision( $post_id ) ) {
return;
}
$new = sanitize_key( $_POST['wpide_new_post_type'] );
if ( $new !== $post->post_type && post_type_exists( $new ) && 'attachment' !== $new ) {
set_post_type( $post_id, $new );
}
}, 10, 2 );
Notes
Categories and tags that the new type does not support stay in the database but are hidden; check the URL afterwards.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.