Permalink Structure for Multiple Post Type Archives by Taxonomy

Here is part of the code from one of my projects to setup a similar structure for permalinks (same base slug for both the post type and the taxonomy archives), please note the values of ‘has_archive’ and ‘rewrite’ parameters of both the post type and the taxonomy:

add_action( 'init', 'register_my_post_types' );
function register_my_post_types() {

  register_post_type( 'movie',
    array(
        ....

        'has_archive' => 'movies',
        'rewrite' => array(
            'slug' => 'movies/%mv_category%',
            'with_front' => false
        ),
        'taxonomies' => array(
            'mv_category',
        ),
    )
  );

  register_taxonomy(
    'mv_category',
    array(
        'movie'
    ),
    array(
        ...
        'hierarchical' => true,
        'rewrite' => array(
            'slug' => 'movies',
            'with_front' => false,
            'hierarchical' => false
        )
    )
  );
) // end of create_my_post_types function


add_filter('post_type_link', 'filter_post_type_link', 10, 2);
function filter_post_type_link($link, $post)
{
    if ($post->post_type != 'movie')
        return $link;

    if ($cats = get_the_terms($post->ID, 'mv_category'))
        $link = str_replace('%mv_category%', array_pop($cats)->slug, $link);

    return $link;
}

Then you can access ‘Documentary’ category of Movie post type with this url:

site.com/movies/documentary/

and ‘Movie A’ of ‘Documentary’ category will be:

site.com/movies/documentary/movie-a/

NOTE: It’s important to register the taxonomy after the post type, because of the order permalink rewrite rules are generated in WordPress.

Leave a Comment