Display CPT list page (archive) with category term on slug

Viewed 38
1 Answers

In that link I found the following solution:


The solution for me had three parts. In my case the post type is called trainings.

  1. Add 'rewrite' => array('slug' => 'trainings/%cat%') to the register_post_type function.
  2. Change the slug to have a dynamic
  3. category. "Listen" to the new dynamic URL and load the appropriate template.

So here is how to change the permalink dynamically for a given post type. Add to functions.php:

function vx_soon_training_post_link( $post_link, $id = 0 ) {
    $post = get_post( $id );
    if ( is_object( $post ) ) {
        $terms = wp_get_object_terms( $post->ID, 'training_cat' );
        if ( $terms ) {
            return str_replace( '%cat%', $terms[0]->slug, $post_link );
        }
    }

    return $post_link;
}

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

...and this is how to load the appropriate template on the new dynamic URL. Add to functions.php:

function archive_rewrite_rules() {
    add_rewrite_rule(
        '^training/(.*)/(.*)/?$',
        'index.php?post_type=trainings&name=$matches[2]',
        'top'
    );
    //flush_rewrite_rules(); // use only once
}

add_action( 'init', 'archive_rewrite_rules' );

Thats it! Remember to refresh the permalinks by saving the permalinks again in de backend. Or use the flush_rewrite_rules() function.


But I have a question that I couldn't do there:

This part:

Add 'rewrite' => array('slug' => 'trainings/%cat%') to the register_post_type function.

where do I do that? Or is this already embedded in the later code?

Related