How to update the custom metadata ( add vendor name from Dokan) of all products on the site?

There is Dokan plugin on the site. Now I need to add the vendor_name to each product, like a custom meta field. And I tried to do something like this:

$args = array(
   'post_type' => 'product',
   'posts_per_page' => -1
);

 $products = new WP_Query( $args );
    if ( $products->have_posts() ):
       while ( $products->have_posts() ):
          
           $vendor_id = get_post_field( 'post_author', get_the_id() );
           $vendor = new WP_User($vendor_id);
           $store_info  = dokan_get_store_info( $vendor_id );
           $store_name  = $store_info['store_name'];   

           $productID = $product->get_id();
           update_post_meta( $productID, 'vendor_name', $store_name );
           $products->the_post();
       endwhile;
  endif;

Thus, I thought to update the metadata for all products. But when I add this code to functions.php The site just stops loading, or rather it loads, but so slowly. There are no errors. Although I may be wrong. Maybe the problem is not in the code, but in the fact that there are more than 18,000 products on the site? Or maybe there is another method to achieve the goal I need. Please help me figure it out.

Answer

You can try to running this code on wordpress action and check some query argument so it does not load on normal view. This is one time process which means you can run this script on your own.

add_action( 'wp', function(){
    if( isset( $_REQUEST['add_vendor_meta'] ) && $_REQUEST['add_vendor_meta'] == 'true' ){
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1
        );

        $products = new WP_Query( $args );
        if ( $products->have_posts() ):
            while ( $products->have_posts() ):
                $products->the_post();
                $vendor_id = get_post_field( 'post_author', get_the_id() );
                $vendor = new WP_User($vendor_id);
                $store_info  = dokan_get_store_info( $vendor_id );
                $store_name  = $store_info['store_name'];   

                $productID = $product->get_id();
                update_post_meta( $productID, 'vendor_name', $store_name );

            endwhile;
            wp_reset_postdata();
        endif;
    }
} );

And also make sure you add wp_reset_postdata() after your while loop end this helps to reset your custom query and doesn’t effect on main query.

Leave a Reply

Your email address will not be published. Required fields are marked *