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