metinsaylan // rogue developer

HowTo: Insert post tags automatically on save

If you want to insert same #tags to every post on your blog post, you can set it to be done automatically using #php. Using this simple #snippet, all tags will be added automatically on save/publish.

*** Everytime you save a post <a href="http://codex.wordpress.org/Plugin_API/Action_Reference/save_post" target="_blank">save_post</a> action runs. Using an #action filter, we will insert our tags to our post. To insert tags, we can use <a href="http://codex.wordpress.org/Function_Reference/wp_set_object_terms" target="_blank">wp_set_object_terms</a>. This function is a great tool to insert tags, #categories, terms on background. Here is the snippet to insert post tags programmatically on save post.

add_action( 'save_post', 'auto_add_post_tags' );
function auto_add_post_tags( $post_id ) {
	if ( !wp_is_post_revision( $post_id ) ) { //verify post is not a revision
		$tag_ids = array();
		
		if( !has_term( 2610, 'post_tag' ) ) { $tag_ids[] = 2610; }
		if( !has_term( 2611, 'post_tag' ) ) { $tag_ids[] = 2611; }
		if( !has_term( 2612, 'post_tag' ) ) { $tag_ids[] = 2612; }
		if( !has_term( 1337, 'post_tag' ) ) { $tag_ids[] = 1337; }
		
		if( count( $tag_ids ) &gt; 0 ) {
			wp_set_object_terms( $post_id, $tag_ids, 'post_tag', true);	
		}
	}
}

Don’t forget to change tag ids of your choice. Enjoy!

(image credit)

Search HowTo: Insert post tags automatically on save on Google