Limit the Number of Tags per Post
Keeps only the first few tags on each post when it is saved, so tag lists stay focused and tag archives do not fill with one-off tags. Writers see a note when extra tags are dropped.
Opens WPIDE on
Code
// Maximum number of tags per post.
$wpide_max_tags = 5;
add_action( 'set_object_terms', function ( $object_id, $terms, $tt_ids, $taxonomy ) use ( $wpide_max_tags ) {
static $running = false;
if ( 'post_tag' !== $taxonomy || $running || count( $tt_ids ) <= $wpide_max_tags ) {
return;
}
$running = true;
$keep = array_slice( array_map( 'intval', $tt_ids ), 0, $wpide_max_tags );
$ids = array();
foreach ( $keep as $tt_id ) {
$term = get_term_by( 'term_taxonomy_id', $tt_id, 'post_tag' );
if ( $term ) {
$ids[] = (int) $term->term_id;
}
}
wp_set_object_terms( $object_id, $ids, 'post_tag' );
set_transient( 'wpide_tags_trimmed_' . get_current_user_id(), 1, 60 );
$running = false;
}, 10, 4 );
add_action( 'admin_notices', function () use ( $wpide_max_tags ) {
if ( get_transient( 'wpide_tags_trimmed_' . get_current_user_id() ) ) {
delete_transient( 'wpide_tags_trimmed_' . get_current_user_id() );
printf( '<div class="notice notice-warning is-dismissible"><p>Only the first %d tags were kept.</p></div>', (int) $wpide_max_tags );
}
} );
Notes
Change $wpide_max_tags; the order is the order in which the tags were added.
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.