custom post types – Different CPT permalink base on taxonomy

Question

I hope someone can help as I has spent few days to sort out but can’t, this is expecting the permalink with category ‘services’ will structure to /products/services/[product-title] and the rest of the category still remain as /products/[product-title]

Custom Post type: Product

A product taxonomy: product-type

product-type categorised by:

  1. chairs
  2. tables
  3. services <- with this type, permalink will change to /products/services/[product-title]

register post type:

$args = array(
    'taxonomies' => array(),
    'has_archive' => false,
    'rewrite' => array('slug' => 'products/%product-type%', 'with_front' => false),
);
register_post_type('product', $args);

register taxonomy:

$args = array(
    'rewrite' => array( 'slug' => 'product-type' ),
);
register_taxonomy( 'product-type', array('product'), $args );

add_filter hook:

function cs_permalink_structure($post_link, $post, $leavename, $sample) {
    if (false !== strpos($post_link, '%product-type%')) {
        $type_term = get_the_terms($post->ID, 'product-type');

        if (!empty($type_term)){
            if($type_term[0]->slug == 'services'){
                $post_link = str_replace('%product-type%', 'services', $post_link);
            }else {
                $post_link = str_replace('%product-type%/', '', $post_link);
            }
        }
    }
    return $post_link;
}
add_filter('post_type_link', 'cs_permalink_structure', 10, 4);

With the hook above, the services category permalink can change to /products/services/[product-title] without 404 error, while I’ve tried replace %product-type% with blank for the rest of other category, with the link /products/[product-title], there is a 404 error.

Is this is something possible can achieve?

** I did re-saved the permalinks in settings.

0
Ben Koo 4 weeks 2022-08-29T04:19:25-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse