Add tag to post api wordpress

I have been googling around but could not find the “add tag to post” api/codex. Does anyone know what it is ? Also, the “delete tag from post”.

Thanks.

Related posts

Leave a Reply

3 comments

  1. You’ll find an index of a good chunk of the WordPress API here on codex. The function you want is wp_set_post_tags(), but follow the links from that page to related functions.

    Edit: this should remove a tag from a post, per comment below

    // $post is your post object, e.g. from: global $post;
    // $target is tag you want to remove
    
    // get an array of current tags on post
    $tags = wp_get_post_tags($post->ID, array('fields' => 'names'));
    
    // remove selected tag from array
    $key = array_search($target, $tags);
    if ($key !== false) {
        unset($tags[$key]);
    }
    
    // set new list of tags, without $target
    wp_set_post_tags($post->ID, $tags, false);
    
  2. Google Knows it.

    If you wanted to add a categories to a post with the ID of 42:

    $cat_ids = array( 6,8 );
        //to make sure the terms IDs is integers:
        //$cat_ids = array_map('intval', $cat_ids);
        //$cat_ids = array_unique( $cat_ids );
    wp_set_object_terms( '42', $cat_ids, 'category' );
    

    If you wanted to clear/remove all categories from a post with the ID of 42:

    wp_set_object_terms( '42', NULL, 'category' );
    

    read more about wp_set_object_terms