How to change custom post type slug without loosing data

Sometime it happens, that at first we create custom post type, register taxonomy and insert some data for that custom post type.

After moving forward, then we realise that, we need to change the slug for that custom post type. There might be some reason for this. Whatever the reason is, when we change the slug for that custom post type, immediately we loose all of our inserted data. Because all of the previous data was stored in the database with the reference of that previous slug.

If you don’t want to loose data, you need to run some query in your database. When you successfully run those query, you will never loose your data.

Let’s assume you have a custom post type named Books and the slug for this custom post type is my-books. You also register a taxonomy named Categories for your Books custom post type and the slug for this taxonomy is my-books-categories.

Custom post type name - Books
Custom post type slug - my-books
Taxonomy name - Categories
Taxonomy slug - my-books-categories

Now, you want to change that custom post type slug from my-books to only books and change taxonomy slug from my-books-categories to books-category only.

Now open you database and at first you check you have all the data for that previous slug.

SELECT
	*
FROM
	wp_posts
WHERE
	post_type = 'my-books';

After successfully run the above query, you will get all the data for your previous slug.

Now it’s time to update the database. Update old slug with the new one. Run below query to update the your data.

UPDATE
	`wp_posts`
SET
	`post_type` = 'books'
WHERE
	`post_type` = 'my-books';

If you run the above statement successfully you will get the success message for this.

Now check you data for the new slug. It will return all of you old data.

SELECT
	*
FROM
	wp_posts
WHERE
	post_type = 'books';

Now it’s time to update the taxonomy. Run below query from your database.

UPDATE
	`wp_term_taxonomy`
SET
	`taxonomy` = 'books-category'
WHERE
	`taxonomy` = 'my-books-categories';

After successfully run the above statement you will get a success message for your query.

Now open your dashboard and reload it. It will show all old data for the new slug.

Thanks.

Leave a comment

Your email address will not be published.