WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I use the following function in order to retrieve tags of a post, remove an element from the array and then set the result to the post:

$post_tags = wp_get_post_terms( $post_id );
foreach ( $post_tags as $key => $tag) {
    $tag_string = http_build_query( $tag );
    if( 0 != strpos( $tag_string , 'tag-to-be-deleted' ) ) {
            unset( $post_tags[$key] );
wp_set_post_terms ($post_id, $post_tags, 'post_tag');

Then I get a bug inside the wp_set_post_terms function, that says the $post_tags parameter should be a string and not an array...what am I doing wrong here?

Any help would be appreciated.

share|improve this question
up vote 2 down vote accepted

Your code looks little clunky, http_build_query() is definitely not meant for such. Also what you are fetching is not simple array, but array of tag objects.

My take:

$post_tags = wp_get_post_terms( $post_id, 'post_tag', array( 'fields'=>'names' ) );
$pos = array_search( 'tag-to-be-deleted', $post_tags );

if( false !== $pos ) {

    unset( $post_tags[$pos] );
    wp_set_post_terms ($post_id, $post_tags, 'post_tag');
share|improve this answer
Also good solution, thank you. – user1567 Jan 12 '11 at 14:19
You should use this one instead of mine, as wp_get_post_terms here returns only the field you want, and it's a array :) – onetrickpony Jan 12 '11 at 16:43
I will, thanks again – user1567 Jan 12 '11 at 20:17

wp_get_post_terms() seems to return a object, and you need to pass a array to wp_set_post_terms:

$post_tags = wp_get_post_terms( $post_id );
$new_tags = array();
foreach ( $post_tags as $tag) {
    $tag_string = http_build_query( $tag );
    if( strpos( $tag_string , 'tag-to-be-deleted' ) === false ) {
            $new_tags[] = $tag->name;
wp_set_post_terms ($post_id, $new_tags, 'post_tag');
share|improve this answer
Excellent, it worked! thanks – user1567 Jan 12 '11 at 14:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.