How to change database values on theme update

I have a theme released into the wild but have not prefixed the post type appropriately. Yes, I know, it’s a shame and I regret it 🙁

So, I am currently using acme as the post type name, but I’ like to change it to prefix_acme.

Read More

I’m looking for the most appropriate function/hook to rename the post type without losing any data so users will not experience a difference.

Can the database values under wp_posts -> post_type simply be changed during a theme update?

If so, then can the same be done for wp_postmeta -> meta_key without losing the meta_value?

Related posts

Leave a Reply

1 comment

  1. This will not be the full answer but i think it will greatly help you if you are able to make templates – you will be able to do this:

    In theme init (when it installs) make function which will make db query to find all post with your post_type and renames post_type to your new value. (i think this is very easy and can be done with 1 query).

    Then make sure your new theme supports that new post_type (just change post_type name) – THAT’s IT! CLients won’t loose anything and you’ll fix it in seconds 🙂

    MAybe this query will do it: (not tested)

    function fixme($oldname, $new_typename){
    global $wpdb;
    $wpdb->query( $wpdb->prepare( "UPDATE ".$wpdb->posts." SET post_type = %s WHERE post_type = %s", $new_typename, $oldname ) );                                                                                                                                                        
    
    }
    

    You can use in function this: $wpdb->prefix if you need to get prefix.

    OR you can use add_action( 'after_setup_theme', 'your_function_name' ); so after theme will be installed it will call your defined function, but then you have to change it to not use parameters to set new post_type but write them manually (assign to $oldname, $new_typename values)

    And YES you can do the same on meta keys too (if they are not sanitized, if they are -then you’ll need php more than in regular situation)..you can do whatever you want with queries, cause they are direct to database.