设置可变产品的销售价格,而不会使它们在 Woocommerce 中缺货

问题描述 投票:0回答:1

我有以下代码:

foreach ($loop->posts as $product) {
$currentPrice = get_post_meta($product->ID, '_regular_price', true);
update_post_meta( $product->ID, '_price', $currentPrice );
update_post_meta( $product->ID, '_regular_price', $currentPrice );  

delete_metadata('post', $product->ID, '_sale_price');
if(in_array($i, $random_product)) {
    $discount = rand(10,25) / 100;
    $salePrice = $discount * $currentPrice;
    $salePrice = ceil($currentPrice - $salePrice);
    if($salePrice == $currentPrice) {
        $salePrice = $currentPrice - 1;
    }
    if($currentPrice != '' || $currentPrice == '0') {
        update_post_meta($product->ID, '_sale_price', $salePrice);
        update_post_meta( $product->ID, '_price', $salePrice );
        echo "Sale Item $i / Product ID $product->ID / Current Price $currentPrice / Sale Price $salePrice \n"; 
    }
}
$i++;
}

基本上我想要做的就是将每个商品通过我的商店,循环它,如果它在我的数组中(这只是随机生成的产品 ID 数组),它应该将它们设置为促销,并确保其他所有商品产品未发售。

但是,当我这样做时......无论出于何种原因,我的所有可变产品都会显示为不可用,直到我进入他们的产品页面并单击变体 -> 设置状态 -> 有货

我以为我会很聪明,将其更改为管理库存,并且有 999 种产品有库存,但仍然产生了同样的问题。

问题是,我不会仅用价格来更改库存...但是,我手动运行的正是这段代码,它触发了问题。

有什么想法吗?

php wordpress woocommerce crud product-price
1个回答
1
投票

您应该尝试使用自 WooCommerce 3 以来新引入的 CRUD 方法,而不是使用 WordPress post 元函数。

我还在您的代码中进行了一些更改,但无法进行测试,因为您的问题代码不完整。尝试如下操作:

foreach ( $loop->posts as $post ) {
    // Get an instance of the product object
    $product = wc_get_product($post->ID);
    
    $changes = false;

    // Get product regular and sale prices
    $regular_price = $product->get_regular_price();
    $sale_price    = $product->get_sale_price();
    
    if( ! empty($sale_price) || $product->is_on_sale() ) {
        // Empty product sale price
        $product->set_sale_price('');

        // Set product active price back to regular price
        $product->set_price($regular_price);
        
        $changes = true;
    }
    
    if( in_array( $i, $random_product ) ) {
        // Calculate a ramdom sale price for the current ramdom product
        $discount_rate = (100 - rand(10, 25)) / 100;
        $sale_price    = ceil($discount_rate * $regular_price);

        // Set product active price and sale price
        $product->set_sale_price($sale_price);
        $product->set_price($sale_price);

        printf( __("Sale Item %s / Product ID %s / Current Price %s / Sale Price %s \n"),
        $i, $post->ID, wc_price($regular_price), wc_price($sale_price) );
        
        $changes = true;
    }
    $i++;
    
    if( $changes ){
        // Save the product data
        $product->save();
    }
}

未经测试

© www.soinside.com 2019 - 2024. All rights reserved.