Post Pic

Add categories or tags to post programatically

I recently shown you jow you can create a post or a comment programatically, which is very usefull when creating advanced WOrdPress themes or plugins. Today, let’s have a look at another killer snippet: Add categories or tags to a posts, programatically.

The first thing to do is to create an array of categories id. Once done, you simply have to use the wp_set_object() function, which take 3 parameters: The post id, an array of categories to add to the post, and the taxonomy type (category in this example).

$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');

Adding tags to a post is extremely easy as well. The only difference with the code to add categories is the taxonomy "post_tag" instead of "category".

$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');

Thanks to WPProgrammer for this very cool snippet.

One Response

Nov 29 2011 06:20

how to Show Related Posts for Custom Post Types and Taxonomies???

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required