Categories
Uncategorized

How to automatically add tags to WordPress posts

This one drove me crazy, but I finally figured it out.

In WordPress, if you need to automatically add tags to a post via a PHP script, the best way to do it is via the wp_set_object_terms() function. There is no handy “wp_insert_tag()” function, or something like that, so look no further.

wp_set_object_terms()

wp_set_object_terms() is a powerful function that not only helps you assign tags to posts (or pages), but also categories and other terms. For this example, here’s the PHP code needed to assign tags to a post.

<?php
   $tags = array('html', 'css', 'javascript');
   wp_set_object_terms( $post_id, $tags, 'post_tag', true );
?>

The code above will create the new tags (or terms) if they don’t exist and link them to the post specified by $post_id.

For more info on this function and its parameter, check out the codex page at http://codex.wordpress.org/Function_Reference/wp_set_object_terms/