Put the Category in Custom Post Type URLs
Builds custom post type URLs with a taxonomy term, such as /books/fantasy/the-hobbit/, which reads better and groups content by section.
Opens WPIDE on
Code
// Post type, taxonomy, URL base and the term slug used when an item has none.
$wpide_term_url = array(
'post_type' => 'book',
'taxonomy' => 'genre',
'base' => 'books',
'fallback' => 'general',
);
add_filter( 'register_post_type_args', function ( $args, $post_type ) use ( $wpide_term_url ) {
if ( $wpide_term_url['post_type'] === $post_type ) {
$args['rewrite'] = array( 'slug' => $wpide_term_url['base'] . '/%' . $wpide_term_url['taxonomy'] . '%', 'with_front' => false );
$args['has_archive'] = $wpide_term_url['base'];
}
return $args;
}, 10, 2 );
add_filter( 'post_type_link', function ( $link, $post ) use ( $wpide_term_url ) {
$tag = '%' . $wpide_term_url['taxonomy'] . '%';
if ( $wpide_term_url['post_type'] !== $post->post_type || false === strpos( $link, $tag ) ) {
return $link;
}
$terms = get_the_terms( $post, $wpide_term_url['taxonomy'] );
$slug = ( $terms && ! is_wp_error( $terms ) ) ? $terms[0]->slug : $wpide_term_url['fallback'];
return str_replace( $tag, $slug, $link );
}, 10, 2 );
Notes
Every item needs a term; items without one use $wpide_term_url['fallback'], so create a term with that slug. Visit Settings > Permalinks once after activating.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.