# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: permalinks, taxonomies, custom-post-types
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/term-in-post-type-permalink/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Put the Category in Custom Post Type URLs" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
