Permalink with sub-sub-category and post name

Working on a new theme project and I created a custom post type called products with its own custom taxonomy.
I want the URL structure to be:

http://example.com/products/main_category/subcategory1/subcategory2/postname/

I found this solution here:

Read More
function filter_post_type_link($link, $post)
    {
        if ($post->post_type == 'products')
            return $link;

        if ($cats = get_the_terms($post->ID, 'product_categories'))
            $link = str_replace('%product_categories%', array_pop($cats)->slug, $link);
        return $link;
    }
    add_filter('post_type_link', 'filter_post_type_link', 10, 2);

With this solution I was able to create this structure:

http://example.com/products/category/postname/

So subcategories still won’t show in the URL…

The other problem is that when I set the taxonomy hierarchical => true the url looks like this when I browse the product categories:

 http://example.com/products/category1/subcategory1-category1/subcategory2-subcategory1-category1/

and also when hierarchical => true is present the code I mentioned above stops working.

So what I want to achieve with product urls basically is this:
If product belongs to the main category:

 http://example.com/products/main_category/postname/

If product belongs to subcategory1:

 http://example.com/products/main_category/subcategory1/postname/

If product belongs to subcategory2:

 http://example.com/products/main_category/subcategory1/subcategory2/postname/

Of course if I delete post name from the above urls wp should show the appropriate category.
This would be a nice hierarchical structure.

Do You know any solutions to make this happen?

Best Wishes,
Matt

Related posts

Leave a Reply

1 comment

  1. Get rid of the filter that you have. Make sure that you use 'rewrite' => array( 'hierarchical' => 'true' ) in your register_taxonomy() function. Don’t forget to flush the rewrite rules. See this page for more info: Codex