WordPress Theme Migration Custom Post Type Issue – Resolved!
by on October 30, 2020 in All

I started this website in 2010. 10 years later, I’m finally switching from my now dead and discontinued old theme to a new theme. The old theme had it’s own custom post types which weren’t being picked up by the new theme.

I had to edit the functions.php – This is just a note to self about what I did… if I change theme again.

This first bit of code goes in the function.php and adds category and tag columns in the custom post type from the previous theme in the new theme. The Custom Post Type Name is ‘mtheme_portfolio. Code comes from here: https://wpsites.net/wordpress-tips/use-categories-and-tags-with-your-custom-post-type/

add_action('init', 'add_category_tags_to_cpt'); function add_category_tags_to_cpt() { register_taxonomy_for_object_type('category', 'mtheme_portfolio'); register_taxonomy_for_object_type('post_tag', 'mtheme_portfolio'); }

This next bit of code also goes into the function.php and allows the custom post type to be found and populated in the blog roll.

function my_get_posts( $query ) { if ( is_home() && $query->is_main_query() ) $query->set( 'post_type', array( 'post', 'mtheme_portfolio' ) ); return $query; }

These next 2 bits of code tidy up the url structure and remove the slug from the Custom Post Type. They come from here: https://permaslug.com/remove-slug-from-cpt-url-in-wordpress/ and needs to be used with a plugin called Code Snippets – haven’t done this yet.

function na_remove_slug( $post_link, $post, $leavename ) { if ( 'events' != $post->post_type || 'publish' != $post->post_status ) { return $post_link; } $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
function na_parse_request( $query ) { if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'events', 'page' ) ); } } add_action( 'pre_get_posts', 'na_parse_request' );
2020 JJROUX.COM © ALL RIGHTS RESERVED