Woocommerce:更新所有产品的功能 [英] Woocommerce: function to update all products

查看:61
本文介绍了Woocommerce:更新所有产品的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Woocommerce 产品有问题.如果我只是更新产品(编辑产品并单击更新"按钮)而不进行任何更改,则此问题已得到解决.

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.

我的网站上有大约 2000 种产品,然后我想使用我的 function.php 文件中的一个函数来实现这一点.

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

推荐答案

尝试以下方法,每次都会更新您的产品 200 以避免出现问题(如果您也有可变产品,post_type 参数需要是 product & product_variation):

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();
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.

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

每次您浏览网站的页面时,都会触发该功能.按 200 处理产品更安全,并且将避免超时或错误.

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.

例如,您可以将该数字增加到 500,将 $limit 设置为 500

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

这篇关于Woocommerce:更新所有产品的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆