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

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: tags, editorial, taxonomies
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/content-limit-tags-per-post/

## Code

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

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit the Number of Tags per Post" 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/
