0

please tell me that you know how to add tags for all products. I tried wp_set_object_terms($post->id, array('nou','product_tag2','product_tag3'), 'product_tag'); but doesn't work. My whole code is:

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');
2
  • If it does not do what you want it to do, what does it do instead? Are you sure it's finding posts to process? Why do you use $post->id in one place, then $post->ID in another, and you don't declare $post as a global either so where is $post coming from? Also wp_set_object_terms can return an error object if it's used incorrectly but the code in your question does not assign it to a variable or attempt to check for this
    – Tom J Nowell
    Jun 29, 2021 at 20:03
  • I don't know php, but I only want my products to have the tag "new". I don't know how I can assign a tag for all my products. Can you help me? Please
    – user208374
    Jun 29, 2021 at 20:12

1 Answer 1

0

This is the solution

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.