0

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.

2

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');
}
|improve this answer|||||
  • 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
1

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');
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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