WP_SET_OBJECT_TERMS不工作

时间:2021-06-29 作者:Răuțu Denis

请告诉我您知道如何为所有产品添加标签。我试过了wp_set_object_terms($post->id, array(\'nou\',\'product_tag2\',\'product_tag3\'), \'product_tag\'); 但不起作用。我的全部代码是:

function add_tags() {
$args = array(
    \'post_type\' => \'product\',
    \'posts_per_page\' => -1
    );
    
$loop = new WP_Query( $args );
if ( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post();

    wp_set_object_terms($post->id, array(\'nou\',\'product_tag2\',\'product_tag3\'), \'product_tag\');

    $terms = get_the_terms( $post->ID, \'product_tag\' );

    $aromacheck = array();

    foreach ( $terms as $term ) {
        $aromacheck[] = $term->slug;
        echo $term->slug;
    }


    if (in_array ( "nou", $aromacheck ) ) { 
        echo "I have the value";
    } 

endwhile; endif; wp_reset_postdata();
}
add_action(\'init\', \'add_tags\');

1 个回复
SO网友:Răuțu Denis

这就是解决方案

function add_tags_products()
{
global $product;


$args = array(
    \'post_type\' => \'product\', // your product post type
    \'posts_per_page\' => - 1,
);

$posts = get_posts($args);

foreach ($posts as $post):
    setup_postdata($post);

    // check to see if the post has any tags
    if( ! has_term( \'\', \'product_tag\', $post->ID ) ) :
        // create the term
        wp_set_object_terms($post->ID, array(\'nou\'), \'product_tag\');
    endif;

    wp_reset_postdata();
endforeach;
}


add_action(\'init\', \'add_tags_products\');