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.
Opens WPIDE on
Code
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 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.