Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce: function to update all products

I have an issue with my Woocommerce products. This issue is fixed if I just update the product (edit the product and click in the Update button) with no changes at all.

I have around 2000 products in my site, then I am thinking of doing this using a function in my function.php file.

It should be something like this, I just need the line which update the product.

function update_all_products(){

    // getting all products
    $products = get_posts( $args );

    // Going through all products
    foreach ( $products as $key => $value ) {

        // the product ID
        $product_id = $value->ID;

        // update product
        update_post_meta...(NEED HELP HERE)...

   } //..end foreach
}

// fire the function
update_all_products();
like image 213
JPashs Avatar asked May 03 '19 07:05

JPashs


People also ask

How do I change the number of products per row in WooCommerce?

Within the WooCommerce plugin, there are settings to change the products per row on a product category page. If you navigate to WordPress Admin > Appearance > Customize > WooCommerce > Product Catalog > products per row you will see these settings below.

Can WooCommerce handle 100000 products?

What is the maximum WooCommerce can handle? Sky is the limit. We've seen instances of shops with 100,000+ products listed, handling thousands of transactions per minute. In those cases, they had great hosting support and their own developer team focused on optimization.


1 Answers

Try the following, that will update your products by 200 each time to avoid problems (if you have variable products also, the post_type arg will need to be product & product_variation):

 add_action( 'woocommerce_loaded', 'update_products_by_x' );
function update_products_by_x(){
    $limit = 200;

    // getting all products
    $products_ids = get_posts( array(
        'post_type'        => 'product', // or ['product','product_variation'],
        'numberposts'      => $limit,
        'post_status'      => 'publish',
        'fields'           => 'ids',
        'meta_query'       => array( array(
            'key'     => '_sync_updated',
            'compare' => 'NOT EXISTS',
        ) )
    ) );

    // Loop through product Ids
    foreach ( $products_ids as $product_id ) {

        // Get the WC_Product object
        $product = wc_get_product($product_id);

        // Mark product as updated
        $product->update_meta_data( '_sync_updated', true );

        $product->save();
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Each time you will browse a page of your site the function will be triggered. processing products by 200 is just more secure and will avoid a timeout or errors.

You can increase that number to 500 for example, setting the $limit to 500

like image 157
LoicTheAztec Avatar answered Oct 05 '22 14:10

LoicTheAztec