Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

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

 
discard

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.