Automatically Add Tags to WordPress Posts Based on Content
Adding relevant tags to your blog posts is crucial for organizing your WordPress site, improving user experience, and boosting SEO. However, manually tagging each post can be time-consuming.
This tutorial explains how to automatically assign tags to your posts using a simple PHP function added to your theme's functions.php file.
Implementation Code
Add the following code to the end of your active theme's functions.php file. Always back up the file before making changes.
/**
* Automatically add existing tags to posts
* Associates tags with a post when their names appear in the post content or title.
*/
add_action('save_post', 'auto_add_tags_to_post');
function auto_add_tags_to_post($post_id) {
// Prevent execution during autosave or revisions
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (wp_is_post_revision($post_id)) {
return;
}
// Get all existing tags
$tags = get_tags(array('hide_empty' => false));
if (!$tags) {
return;
}
// Get the current post's content and title
$post = get_post($post_id);
$post_content = $post->post_content . ' ' . $post->post_title;
$tags_to_add = array();
foreach ($tags as $tag) {
// Check if the tag name appears in the content/title (case-insensitive)
if (stripos($post_content, $tag->name) !== false) {
$tags_to_add[] = $tag->name;
}
}
// Add matched tags to the post (append, do not overwrite)
if (!empty($tags_to_add)) {
wp_set_post_tags($post_id, $tags_to_add, true);
}
}
How It Works & Important Notes
- Trigger: The function hooks into the
save_postaction, running automatically when a post is saved or updated. - Matching Logic: It checks the post's content and title for the names of existing tags (case-insensitive). If a match is found, that tag is associated with the post.
- Append Mode: The third parameter in
wp_set_post_tagsis set totrue, meaning new tags are added without removing existing ones. - Performance: If your site has a very large number of tags, this function may slightly slow down post publishing. Regularly clean up unused tags to maintain efficiency.
- Recommendation: This method works best for sites where content strongly correlates with tag names. For new sites, it's advisable to first build a core set of tags manually.
Next Step: Automatic Internal Linking
After implementing auto-tagging, you might want these tags to be automatically linked within your post content to their archive pages, further improving internal linking and SEO.
This requires a separate function that filters the post content, replacing tag names with hyperlinks. Implementation must be careful to avoid replacing text inside HTML tags and prevent infinite loops. For stability and performance, consider using a dedicated plugin or a more comprehensive code solution.
Combining automatic tagging with automatic internal linking can significantly enhance your site's content structure and SEO foundation, making content management more efficient.