![](/img/trans.png)
[英]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.