Remove Parent Categories from URL of custom post type: product – wordpress

Just as the title says.

I’ve been searching all morning for a solution and have yet to find one that works for the custom post type of “product”

Read More

current url structure:

shop.com/mens/clothing/shirts

desired url when on clothing category page:

shop.com/clothing

and when on the shirts category page:

shop.com/shirts

So basically, only show the current level category in the url.

I know it seems weird with this simplified example, but trust me..this is exactly what I need.

I’ve found tons of resources to do this with regular post types, but not the product post type.

Please help

Edit 1
This is a popular piece of code mentioned around the web, but it doesn’t work in my case. I am assuming it is because I am trying to do this with custom post types.

add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename ){
    $cats = get_the_category( $post->ID );
    if ( $cats ) {
        // Make sure we use the same start cat as the permalink generator
        usort( $cats, '_usort_terms_by_ID' ); // order by ID
        $category = $cats[0]->slug;
        if ( $parent = $cats[0]->parent ) {
            // If there are parent categories, collect them and replace them in the link
            $parentcats = get_category_parents( $parent, false, '/', true );
            // str_replace() is not the best solution if you can have duplicates:
            // myexamplesite.com/luxemburg/luxemburg/ will be stripped down to     myexamplesite.com/
            // But if you don't expect that, it should work
            $permalink = str_replace( $parentcats, '', $permalink );
        }
    }
    return $permalink;
}

Related posts

1 comment

  1. You can achieve this using following code snippet,

    function wdm_remove_parent_category_from_url( $args ) {
        $args['rewrite']['hierarchical'] = false;
        return $args;
    }
    
    add_filter( 'woocommerce_taxonomy_args_product_cat', 'wdm_remove_parent_category_from_url' );
    

Comments are closed.