I use post_type_link to change the URL for a custom post type "products". I want the URL to be "www.domain.se/parent-taxonomy/taxonomy/post-name".

Using this guide: https://wsidmg.com/change-url-structure-of-custom-post-type-and-custom-taxonomy-in-wordpress/ I now have the following code and it creates my URL perfect. Though It give me a 404 when going to a post.

If I remove the / for $termurl it works, so the problem is that I add another /. Right? Any one know why?

function create_hierarchy_permalink( $post_link, $id = 0, $leavename = false ) {

    if( strpos($post_link, '%productcategory%')){
        $post = get_post($id);

        if ( !is_object($post) || $post->post_type != 'products' ) {
            return $post_link;

        $terms = get_the_terms($post->ID, 'productcategory');

        if ( !$terms ) {
            return str_replace('/%productcategory%/', '', $post_link);

        $parent = get_term($terms[0]->parent, 'productcategory');
        $term = array_pop($terms);
        $termurl = $parent->slug . '/' . $term->slug;

        return str_replace('%productcategory%', $termurl, $post_link);

add_filter('post_type_link', 'create_hierarchy_permalink', 1, 3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.