Create and insert wordpress product tags programatically using wp_set_object_terms

Viewed 1162

I have around 2000 products which has no tags. Now i want to update tag for those products. I want to set post_title=tag for all 2000 products.

Below code works for a product to set CUSTOM TAG to PRODUCT

wp_set_object_terms($productID, array('product_tag1','product_tag2','product_tag3'), 'product_tag');

Instead of complicating the work from front end for each product.

Can someone please guide me how to set post_title=tag using php for all my products.

1 Answers

You can loop through your products and assign the tags, maybe something like this:

Update: If you want to just add a tag to posts which dont have any existing tags, you could do something like this:

<?php
add_action('init', 'add_tags_products');

function add_tags_products()
{
    $args = array(
        'post_type' => 'products', // your product post type
        'posts_per_page' => - 1,
    );

    $posts = get_posts($args);

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

        // get the title of the post
        $title = get_the_title($post->ID);

        // 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($title), 'product_tag');
        endif;

        wp_reset_postdata();
    endforeach;

}

Paste the above code in your index.php file for testing and visit the site, and after all the tags are set, remove it. Also backup first in case something happens.

Related