[英]Enable or disable WooCommerce products sale price based on URL variable
[英]Set sale price on Variable Products without making them out of stock in Woocommerce
我有以下代码:
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 种产品有库存,但仍然会产生同样的问题。
问题是,我不会只用价格来改变股票......但是正是这个代码我手动运行了它并触发了问题。
有什么想法吗?
您应该尝试使用自 WooCommerce 3 以来新引入的CRUD 方法,而不是使用 WordPress 后元函数。
我还对您的代码进行了一些更改,但由于您的问题代码不完整,因此无法对其进行测试。 尝试类似以下内容:
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();
}
}
未经测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.