【发布时间】:2018-11-07 12:56:13
【问题描述】:
在 Woocommerce 中,我想在单个产品页面和相关购物车项目上更改特定产品(在本例中 ID 为 87)的价格。
产品价格需要增加 10 美元,但只能在单个产品页面上,并且只能在外部(这样 Woocommerce 中设置的内部价格或价格不会改变)。
此外,此价格也应在购物车中更改,但前提是某个类别的产品不在购物车中。
背景:如果有人单独购买此产品,则应向他们收取高于正常价格 10 美元的费用。如果有人与某个类别的产品一起购买此商品,则应向他们收取正常价格。 这本质上是一种反向折扣(我不想使用优惠券功能收取额外费用)。
对于购物车功能,到目前为止,我有这个,但它不起作用 - 当当前的常规/基本价格为 45 美元时,购物车价格为 75 美元。我不知道 75 应该是 55 是从哪里来的。
function wc_cart_custom_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// set our flag to be false until we find a product in that category
$cat_check = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'your-category' with your category's slug
if ( has_term( 'your-category', 'product_cat', $product->id ) ) {
$cat_check = true;
// break because we only need one "true" to matter here
break;
}
}
// if a product in the cart is in our category, stop there and don't change price
if ( $cat_check ) {
return;
}
// else continue and alter the product price
else if ( $cart_item['product_id'] == 87 ) {
// we have the right product, do what we want
$price = $cart_item['data']->get_price(); // Get the product price
$new_price = $price + 10; // the calculation
$cart_item['data']->set_price( $new_price ); // Set the new price
}
}
add_action( 'woocommerce_before_calculate_totals', 'wc_cart_custom_price' );
目前我更改产品页面价格的代码是:
function wc_change_product_price($price, $product) {
if ( is_single('87') ) {
$post_id = $product->id;
$regular_price = get_post_meta( $post_id, '_regular_price', true);
$custom_value = ( $regular_price + 10 );
$price = $custom_value;
return $price;
}
}
add_filter('woocommerce_get_price', 'wc_change_product_price', 99);
这是一场灾难并导致 500 服务器错误。我做错了什么?欢迎任何帮助。
参考资料:
Change cart item prices in WooCommerce version 3.0
https://rudrastyh.com/woocommerce/change-product-prices-in-cart.html
https://www.skyverge.com/blog/checking-woocommerce-cart-contains-product-category/
【问题讨论】:
标签: php wordpress woocommerce custom-taxonomy price