【发布时间】:2016-08-07 03:45:40
【问题描述】:
是否可以在 Woocommerce 迷你购物车小部件中更改产品价格?我已经使用来自WooCommerce: Add product to cart with price override? 的提示覆盖了购物车中的价格,但它仅适用于购物车页面。小部件中的价格没有变化。
【问题讨论】:
标签: javascript php jquery wordpress woocommerce
是否可以在 Woocommerce 迷你购物车小部件中更改产品价格?我已经使用来自WooCommerce: Add product to cart with price override? 的提示覆盖了购物车中的价格,但它仅适用于购物车页面。小部件中的价格没有变化。
【问题讨论】:
标签: javascript php jquery wordpress woocommerce
您可以使用“woocommerce_cart_item_price”过滤器,而不是使用“woocommerce_before_calculate_totals”,例如
add_filter('woocommerce_cart_item_price','modify_cart_product_price',10,3);
function modify_cart_product_price( $price, $cart_item, $cart_item_key){
$price = wc_price($custom_price, 4);
return $price;
}
【讨论】:
这就是我将免费产品的价格设置为 0 的方式:
function set_free_items_price( $price, $cart_item, $cart_item_key ) {
$returned_item_price = $cart_item['data']->get_price();
if (isset($cart_item['free_item']['value'])
&& $cart_item['free_item']['value'] == true) {
$returned_item_price = 0;
}
return get_woocommerce_currency_symbol() . $returned_item_price;
}
我在课堂上钩住了,所以钩子看起来像这样:
add_filter( 'set_free_items_price', array(__CLASS__, 'woocommerce_cart_item_price_filter'), 10, 3 );
但如果你将它用作程序函数,你的钩子应该是这样的:
add_filter( 'set_free_items_price', 'woocommerce_cart_item_price_filter', 10, 3 );
请记住,这也会影响常规购物车中的 price 行。 而且,如果您没有看到迷你购物车的变化,请尝试在常规购物车页面上更新购物车,然后返回并再次检查迷你购物车的值是否已更改。
【讨论】:
要更改 WooCommerce 迷你购物车小部件的价格,您必须使用此过滤器挂钩:woocommerce_widget_cart_item_quantity
您可以查看文件的第 63 行:woocommerce/templates/cart/mini-cart.php 以查看过滤器挂钩是如何创建的。
apply_filters( 'woocommerce_widget_cart_item_quantity', '<span class="quantity">' . sprintf( '%s × %s', $cart_item['quantity'], $product_price ) . '</span>', $cart_item, $cart_item_key );
正如过滤器挂钩的名称所示,它不仅可以用于价格,还可以用于显示数量。
例如,您可以使用它根据条件对某些产品应用折扣。在这种情况下,我使用了存储在产品元数据中的值。
add_filter('woocommerce_widget_cart_item_quantity', 'custom_wc_widget_cart_item_quantity', 10, 3 );
function custom_wc_widget_cart_item_quantity( $output, $cart_item, $cart_item_key ) {
$product_id = $cart_item['product_id'];
// Use your own way to decide which product's price should be changed
// In this case I used a custom meta field to apply a discount
$special_discount = get_post_meta( $product_id, 'special_discount', true );
if ($special_discount) {
$price = $cart_item['data']->get_price();
$final_price = $price - ( $price * $special_discount );
// The final string with the quantity and price with the discount applied
return sprintf( '<span class="quantity">%s × <span class="woocommerce-Price-amount amount">%s <span class="woocommerce-Price-currencySymbol">%s</span></span></span>', $cart_item['quantity'], $final_price, get_woocommerce_currency_symbol() );
} else {
// For the products without discount nothing is done and the initial string remains unchanged
return $output;
}
}
请注意,这只会更改价格的显示方式,如果您必须在内部更改价格,也请使用此操作挂钩:woocommerce_before_calculate_totals
【讨论】: