在 Woocommerce 中,我在产品中设置了两个自定义字段:
iadi_price
获取定制销售价格。 iadi_date
用于自定义日期。如果指定日期与今天之间的间隔少于 3 天,我想更新销售价格。
我写了以下代码:
function fiyatidegistir() {
global $product;
$bugun = time();
$yenifiyat = get_post_meta($product->ID, 'iadi_price', true); //new sale price
$kgn = get_post_meta($product->ID, 'iadi_date', true); // date
if(!empty($kgn)) {
$kalan = $kgn - $bugun;
$dakika = $kalan / 60;
$saat = $dakika / 60;
$gun = $saat / 24;
$yil = floor($gun/365);
$gun_farki = floor($gun - (floor($yil) * 365));
if($gun_farki<4 && !empty($yenifiyat)) {
update_post_meta($product->ID, '_price', $yenifiyat);
}
}
}
add_action( 'woocommerce_before_main_content', 'fiyatidegistir');
但是它不起作用,什么也没有发生。
我做错了什么?如何根据解释的价格和日期自定义字段以编程方式更改产品售价?
这样做并不是一个好主意,因为:
此外,您的代码充满了有关 Woocommerce 中的 WC_Products 和日期计算的错误。最后一件事,当你编写代码时,最好用英语命名变量和函数,也用英语注释你的代码,因为任何人都可以理解。
而是尝试以下适用于简单产品的方法,当您的条件匹配时(日期和自定义价格)显示相关产品的促销价格:
add_filter( 'woocommerce_product_get_price', 'conditional_product_sale_price', 20, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'conditional_product_sale_price', 20, 2 );
function conditional_product_sale_price( $price, $product ) {
if( is_admin() ) return $price;
$new_price = get_post_meta( $product->get_id(), 'iadi_price', true ); //new sale price
$date = get_post_meta( $product->get_id(), 'iadi_date', true ); // date
if( ! empty($date) && ! empty($new_price) ) {
$date_time = (int) strtotime($date); // Convert date in time
$now_time = (int) strtotime("now"); // Now time in seconds
$one_day = 86400; // One day in seconds
// Calculate the remaining days
$remaining_days = floor( ( $date_time - $now_time ) / $one_day );
if( $remaining_days >= 0 && $remaining_days < 4 )
$price = $new_price;
}
return $price;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。已测试并有效。
如果您来这里是为了使其能够适应各种变化,您需要以下所有过滤器:
add_filter( 'woocommerce_product_get_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_variation_prices_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_variation_prices_sale_price', 'conditional_product_sale_price', 10, 2 );
并且您需要确保由于存储的瞬态而更改了 woocommerce_get_variation_prices_hash。
您可能会发现我为客户创建的要点很有用