Post Type Switcher and WPML fix

The Post Type Switcher plugin by John James Jacoby is a really handy way to convert an existing post to a new or different post type. Imagine, for example, that you’ve been maintaining a site for a while, using classic WordPress posts and categories to publish information about your products. But the day has come when your products really need to be defined separately from other editorial content you publish on your site. Once you’ve created your new Products post type (either by using a plugin or hiring a professional like myself), Post Type Switcher lets you move those existing articles from Posts to Products with the click of a button. Pretty sweet.

Now imagine that your website exists in more than one language. Hopefully, you are using WPML to manage that multi-lingual content, as in my mind it’s the best plugin out there right now. As of this writing, Post Type Switcher does not handle the conversion of your posts for more than one language, and unless you manually go into your database and update the appropriate tables, your content kinda gets lost in the mix. It will actually disappear from your admin view. Not good.

Thanks to this WordPress.org forum post by turegjorup, there is a solution.

Disable the plugin if it’s already active, then, from the plugin’s folder, open the file post-type-switcher.php, and just after the line set_post_type( $post_id, $new_post_type_object->name ); add the following code:

if(function_exists('icl_object_id')){
// adjust field 'element_type' in table 'wp_icl_translations'
// from 'post_OLDNAME' to 'post_NEWNAME'
// the post_id you look for is in column: 'element_id'

     if($post->post_type == 'revision'){
	if(is_array($post->ancestors)){
	     $ID = $post->ancestors[0];
	}
     } else {
	$ID = $post->ID;
	}
     global $wpdb;

     $wpdb->update(
          $wpdb->prefix.'icl_translations',
	  array('element_type' => 'post_' . $new_post_type_object->name,	), // string
	  array('element_id' => $ID,'element_type' => 'post_' . $post->post_type)
	  );

     $wpdb->print_error();
}

Reactivate the plugin, and you’re good to go. I also tested the Convert Post Types plugin by Stephanie Leary, which presents the same conflict. I’m sure a similar fix could be created for it as well.

Jenny Beaumont

Jenny Beaumont is an Agile Coach and the Director of Delivery at Human Made, makers of Altis DXP. She speaks at conferences around the world (ok, these days only on zoom), and is a former lead organizer of WordCamp Paris and WordCamp Europe.

Follow me on Twitter | Subscribe to my newsletter