首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >动态折扣Woocommerce产品

动态折扣Woocommerce产品
EN

Stack Overflow用户
提问于 2018-05-29 19:59:42
回答 1查看 937关注 0票数 -1

我想要做的是为我的每个Woocommerce产品采用常规价格,并根据几个条件动态创建销售价格。这将包括以下内容:

1)在商店页面产品上显示动态创建的销售价格。2)购物车中显示的销售价格(购物车中的项目价格和合计反映动态销售价格) 3)结账页面和合计反映动态销售价格。

在研究了几种解决方案后,我提出了以下解决方案:

代码语言:javascript
运行
复制
// Generating dynamically the product "regular price"
add_filter( 'woocommerce_product_get_regular_price', 
'custom_dynamic_regular_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 
'custom_dynamic_regular_price', 10, 2 );
function custom_dynamic_regular_price( $regular_price, $product ) {
if( empty($regular_price) || $regular_price == 0 )
    return $product->get_price();
else
   return $regular_price;
}


// Generating dynamically the product "sale price"
add_filter( 'woocommerce_product_get_sale_price', 
'custom_dynamic_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 
'custom_dynamic_sale_price', 10, 2 );
function custom_dynamic_sale_price( $sale_price, $product ) {
$rate = 0.7;
if( empty($sale_price) || $sale_price == 0 )
    return $product->get_regular_price() * $rate;
else
    return $sale_price;
};

// Displayed formatted regular price + sale price
add_filter( 'woocommerce_get_price_html', 'custom_dynamic_sale_price_html', 
20, 2 );
function custom_dynamic_sale_price_html( $price_html, $product ) {
if( $product->is_type('variable') ) return $price_html;

$price_html = wc_format_sale_price( wc_get_price_to_display( $product, 
array( 'price' => $product->get_regular_price() ) ), 
wc_get_price_to_display(  $product, array( 'price' => $product- 
>get_sale_price() ) ) ) . $product->get_price_suffix();

return $price_html;
} 

add_action( 'woocommerce_before_calculate_totals', 
'set_cart_item_sale_price', 10, 1 );
function set_cart_item_sale_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// Iterate through each cart item
foreach( $cart->get_cart() as $cart_item ) {
    $price = $cart_item['data']->get_sale_price(); // get sale price
    $cart_item['data']->set_price( $price ); // Set the sale price
}
}


add_filter( 'woocommerce_cart_item_price', 
'bbloomer_change_cart_table_price_display', 30, 3 );

function bbloomer_change_cart_table_price_display( $price, $values, 
$cart_item_key ) {
$slashed_price = $values['data']->get_price_html();
$is_on_sale = $values['data']->is_on_sale();
if ( $is_on_sale ) {
$price = $slashed_price;
}
return $price;
}

除了购物车表格合计显示的是原始价格合计,而不是动态销售价格合计之外,这种方法是有效的。肯定有一种更简单的方法来做这件事。任何帮助都将不胜感激。谢谢,朱尔斯

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50583862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档