Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.