# Limit Posts to a Single Category

> Keeps every post in exactly one category: when several are ticked, only the most specific one is kept on save, which keeps URLs, breadcrumbs and archives tidy.

- Type: PHP
- Runs: Run everywhere
- Category: [Admin](https://wpide.com/library/category/admin/)
- Tags: categories, editorial, posts
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/admin-limit-to-one-category/

## Code

```php
add_action( 'set_object_terms', function ( $object_id, $terms, $tt_ids, $taxonomy ) {
    static $running = false;

    if ( 'category' !== $taxonomy || count( $tt_ids ) < 2 || $running || 'post' !== get_post_type( $object_id ) ) {
        return;
    }

    $chosen = null;
    $depth  = -1;
    foreach ( wp_get_object_terms( $object_id, 'category' ) as $term ) {
        $d = count( get_ancestors( $term->term_id, 'category', 'taxonomy' ) );
        if ( $d > $depth || ( $d === $depth && $term->term_id < $chosen ) ) {
            $depth  = $d;
            $chosen = $term->term_id;
        }
    }

    if ( $chosen ) {
        $running = true;
        wp_set_object_terms( $object_id, array( (int) $chosen ), 'category' );
        $running = false;
    }
}, 10, 4 );
```

## Notes

The deepest child category wins; between categories at the same level the one with the lowest ID is kept.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit Posts to a Single Category" 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/
