Skip to content

Add a Category or Tag to a post programatically

$post_id = 1;
// Adding category to the post
$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');
// Adding tags to the post
$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');

Categories: .

Comment Feed

8 Responses

  1. Whats the filter or action to call this?

    • It can be added anywhere after the core API (taxonomy functions) is loaded. Not sure if you were asking for this.

      Utkarsh KukretiAugust 10, 2010 @ 11:33 pmReply
  2. What if you dont know the post id? You just want to add the category to all posts in a custom post type? Like all posts in designer get the category designer automatically?

  3. And is this added in the functions.php file?

  4. What if I need to add a tag to all the posts in a given category?
    ex. tag= blue in category= sky

  5. This code should do it:

    ID; // Get post ID for each post in category.
    $i++; // $i increments to go through array each cycle through the loop.
    //Here’s where you want to include the code that adds the tag to each post. (each time through the loop, it’s working with a new post)
    This function, you can just take out ‘numberposts=10’ to go through all posts in category (I haven’t double checked that, but it should work)
    $postslist = get_posts(‘numberposts=10& category=1’);

    Here’s all the functions used for further options:
    array() –> just look up php array for more details
    get_posts() –>
    *You need the category ID here. To make things a lot simpler, you can install this plugin to show ID’s of posts and categories on admin pages for WP 3.0:

    foreach ($postslist as $post) {} – make sure you have those open/close squiggly brackets around function.

    Of course adjust the opening and closing php tags according to context.

    I could go into further detail, but given you made this comment 2month ago, you’ll probably never see this. Anyone who would like more help, feel free to e-mail me at:


  6. Hmm.. the top half got hacked off. Here is the code again, above the commentary:

    $i = 0; //number in array before loop starts
    $allposts = array();
    $postslist = get_posts(‘numberposts=10&category=1’);
    foreach ($postslist as $post){
    $allposts[$i] = $post->ID; //get post id for each post
    // code to apply to each post goes here. use $allposts[$i] as the post (basically accounts for all of them) you want to edit.

Some HTML is OK

or, reply to this post via trackback.