# Tag Posts Automatically From a Keyword List

> Adds tags to posts when they are saved if the title or content mentions keywords you define, for example tagging every post that mentions "WooCommerce" or "Gutenberg", so tagging stays consistent.

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

## Code

```php
// Keyword (whole word) => tag name.
$wpide_keyword_tags = array(
    'woocommerce'  => 'WooCommerce',
    'block editor' => 'Gutenberg',
    'gutenberg'    => 'Gutenberg',
    'seo'          => 'SEO',
);

// Runs after the editor has saved its own tags, so they are never overwritten.
add_action( 'wp_after_insert_post', function ( $post_id, $post ) use ( $wpide_keyword_tags ) {
    if ( 'post' !== $post->post_type || wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || 'auto-draft' === $post->post_status ) {
        return;
    }

    $text = wp_strip_all_tags( $post->post_title . ' ' . $post->post_content );
    $add  = array();
    foreach ( $wpide_keyword_tags as $keyword => $tag ) {
        if ( preg_match( '/\b' . preg_quote( $keyword, '/' ) . '\b/i', $text ) ) {
            $add[] = $tag;
        }
    }

    if ( $add ) {
        wp_set_post_tags( $post_id, array_unique( $add ), true ); // Append, keep existing tags.
    }
}, 20, 2 );
```

## Notes

Map keywords to tag names in $wpide_keyword_tags; matching is whole-word and case-insensitive, and existing tags are never removed.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Tag Posts Automatically From a Keyword List" 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/
