Change name of a custom post type without losing data

Let’s say you create a custom post type and for some reason, you realize that it has to be changed.

If there is no data stored yet, it shouldn’t be a problem. Change the old custom post type into the new one, save the permalinks again and that’s it. You’re good to go.

It gets a bit more complicated if you already have data stored in that custom post type.

I used the following 2 ways of achieving this.

Some steps that you need to take before changing the name of a custom post type.

  • Create a database backup.
  • Make sure you create the new custom post type.
  • Create a single or archive template for the new custom post type, you can easily copy the one that you currently use on the old custom post type. This way data will be displayed correctly.
  • Update any code that has references to the old custom post type, change that to reflect the new custom post type.

1. Use MySQL to do an UPDATE/REPLACE

Before going with this option make sure you have a database backup. DO NOT implement this if you don’t have a backup.

If you have access to MySQL you can run the following command in order to replace the old custom post type

					

UPDATE `wp_posts`
SET 
    # Update the post_type column
    `post_type` = REPLACE(`post_type`,'name_of_old_post_type','name_of_new_post_type'),
    # Update the urls
    `guid` = REPLACE(`guid`,'name_of_old_post_type','name_of_new_post_type')
WHERE `post_type` = 'name_of_old_post_type'

This option won’t work perfectly if you saved data in serialized arrays. For example, if you saved something in wp_postmeta associated with that custom post type.
Works well if you are using Advanced Custom Fields.

2. Use a plugin like Post Type Switcher

This is a very simple option. You get the Post Type Switcher plugin and after you install it a new option will be available for each post type where you can change its type.

I didn’t encounter any issues while using it.

The nice thing about using this plugin is that you don’t have to mess directly with the database and you can move just the elements that you want to a different custom post type.

 

George-Paul Crețu

Web developer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.