Woocommerce:更新所有产品的功能

JPa*_*shs 5 php wordpress product woocommerce

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

我的站点中有大约 2000 种产品,然后我想使用我的 function.php 文件中的函数来执行此操作。

应该是这样的,我只需要更新产品的行。

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();
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 6

尝试以下操作,每次都会将您的产品更新 200 以避免出现问题 (如果您也有可变产品,则post_typearg 将需要为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();
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。

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

你可以增加数到500,例如,设置$limit500