How to add the term name to a custom post type permalink
By default the permalink of a custom post type (CPT) contains only the post type slug and the post slug. But sometimes the URL has to contain the term too.
Problem: We have a CPT resource with the slug resources/download-center and the taxonomy resource_category. The posts must have the permalink /resources/term-name/post-title/, and the archive page must be /resources/.
Solution: Put a placeholder for the term in the rewrite slug, replace it in the permalinks, and tell WordPress what the placeholder means. Let’s go step by step.
Step 1. The rewrite slug and the archive
In the function where the CPT is registered, instead of 'rewrite' => array( 'slug' => 'resources/download-center' ) write 'rewrite' => array( 'slug' => 'resources/%cat%' ).
The archive also has to be set explicitly, otherwise it would get the slug with the placeholder and /resources/ would be a 404. Instead of 'has_archive' => true use 'has_archive' => 'resources':
<?php
$args = array(
// ...
'rewrite' => array( 'slug' => 'resources/%cat%', 'with_front' => false ),
'has_archive' => 'resources',
// ...
);
Step 2. Replace the placeholder and register it
In functions.php:
<?php
// Put the term slug into the resource permalinks
add_filter( 'post_type_link', 'resource_permalink_term', 10, 2 );
function resource_permalink_term( $post_link, $post ) {
if ( 'resource' !== $post->post_type || false === strpos( $post_link, '%cat%' ) ) {
return $post_link;
}
$terms = wp_get_object_terms( $post->ID, 'resource_category' );
if ( ! is_wp_error( $terms ) && $terms ) {
$post_link = str_replace( '%cat%', $terms[0]->slug, $post_link );
}
return $post_link;
}
// Tell WordPress what %cat% means in the URL
add_action( 'init', function () {
add_rewrite_tag( '%cat%', '([^/]+)', 'resource_category=' );
}, 5 );
The rewrite tag must be added before the post type is registered (priority 5 runs before the usual 10). Then WordPress itself builds the rules for /resources/term/post/, and the archive with its pagination (/resources/page/2/) keeps working.
After that, go to Settings → Permalinks and click Save Changes.
Without the rewrite tag
My first version had a custom rule instead of add_rewrite_tag():
<?php
add_action( 'init', function () {
add_rewrite_rule( '^resources/(?!page/)([^/]+)/([^/]+)/?$', 'index.php?resource=$matches[2]', 'top' );
} );
It also works, but note the (?!page/): without it, /resources/page/2/ matches this rule and the archive pagination returns a 404.
NOTE: Every resource needs a term. Without one the link keeps %cat%. Make the taxonomy required in the editor, or set a default term when the post is saved. If a post has several terms, the first one is used.
Sources: