I'm working with a wordpress theme I purchased for a glassblowing business and it provides me with a custom post type called "portfolio".
What I'm trying to do is rewrite the slug of that custom post type to match the type of product it is.
If the product were under the "lighting" category, the URL would be domain.com/lighting/product-name
If the product were under the "object" category, the URL would be domain.com/objects/product-name
I can get the desired permalink structure for my posts by adding the following code to my child theme's functions.php, but when I do, all of my other pages (minus the home page) return a 404.
add_filter( 'register_post_type_args', 'dynamic_keep_product_slug', 10, 2 );
function dynamic_keep_product_slug( $args, $post_type ) {
if ( 'portfolio' === $post_type ) {
$my_args = array(
'rewrite' => array( 'slug' => '%project-type%', 'with_front' => true ),
'hierarchical' => true,
'taxonomies' => array('category')
);
return array_merge( $args, $my_args );
}
return $args;
}
function keep_product_link( $post_link, $id = 0 ) {
$post = get_post($id);
$terms = wp_get_object_terms( $post->ID, 'project-type' );
if( $terms ){
return str_replace( '%project-type%' , $terms[0]->slug , $post_link );
} else {
return str_replace( '%project-type%' , 'products' , $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'keep_product_link', 10, 2 );
I'm far from an expert, so can someone tell me where I've gone wrong here? Is there a better way of giving this post type multiple slug options?