Hack: Automatically Add a Tag Based On Post Title and Content

The worst part about using tags sometimes is forgetting to apply them. You can fix that problem for some of your most important tags by using a simple hack that looks at the title and content of your post every time you update it. If it finds a word in there, then the tag is automatically added.

add_action('publish_post','wpaction_autoadd_tags');
function wpaction_autoadd_tags($id) {
	$post = get_post($id);
	$string = $post->post_title . $post->post_content;
	if (stripos($string, 'testing') !== FALSE) wp_set_post_tags($id,'testtag',true);
}

This code adds an action during the publish_post hook. It grabs the post, and then creates a string with the title and the content. You could choose one or the other instead. It then uses a simple stripos function to look for the word, case-insensitive.

If it finds the word, it adds the tag using wp_set_post_tags with the third parameter true, so the tag is added to whichever tags are already there. You can simply repeat that last line a few times for a few words and tags. Or, if you have a lot, you can create an array and loop through it.

This basic premise can also be used to look at categories or any other property of the post. Heck, you could also look at combinations of things.

The code can be placed in either your own custom plugin, or the functions.php file of your theme.

Leave a Reply

Your email address will not be published. Required fields are marked *