从woocommerce功能中排除购物车中的产品



我们运行这个函数,其中作为产品的数量>1、折扣费加到购物车里。问题是,如果特定产品在购物车中,则需要排除此功能。这是代码:

add_action( 'woocommerce_cart_calculate_fees', 'wpf_wc_add_cart_fees_by_cart_qty' );
if ( ! function_exists( 'wpf_wc_add_cart_fees_by_cart_qty' ) ) {
/**
* wpf_wc_add_cart_fees_by_cart_qty.
*/
function wpf_wc_add_cart_fees_by_cart_qty( $cart ) {
$qty = $cart->get_cart_contents_count();
if ( $qty > 1 ) {
$name      = 'Korting meerdere deelnemers';
$amount    = -10;
$taxable   = true;
$tax_class = '';
$cart->add_fee( $name, $amount, $taxable, $tax_class );
}
}
}

现在我已经添加了一行检查产品是否在购物车中,但它不起作用:

add_action( 'woocommerce_cart_calculate_fees', 'wpf_wc_add_cart_fees_by_cart_qty' );
if ( ! function_exists( 'wpf_wc_add_cart_fees_by_cart_qty' ) ) {
/**
* wpf_wc_add_cart_fees_by_cart_qty.
*/
$product_id = 12345;
if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product_id ) ) ) {
// Yes, it is in cart, do nothing. 
}else{
function wpf_wc_add_cart_fees_by_cart_qty( $cart ) {
$qty = $cart->get_cart_contents_count();
if ( $qty > 1 ) {
$name      = 'Korting meerdere deelnemers';
$amount    = -10;
$taxable   = true;
$tax_class = '';
$cart->add_fee( $name, $amount, $taxable, $tax_class );
}
}
}
}

我做错了什么?

我尝试添加产品是否在购物车中的检查。如果是,什么都不做。如果为false,则运行该函数。

你在函数外面写if/else。下面是更正后的代码:

注意:如果任何编码错误导致任何致命错误,请确保您有FTP访问权限来纠正代码。

add_action( 'woocommerce_cart_calculate_fees', 'wpf_wc_add_cart_fees_by_cart_qty' );
if ( ! function_exists( 'wpf_wc_add_cart_fees_by_cart_qty' ) ) {
function wpf_wc_add_cart_fees_by_cart_qty( $cart ) {
// Define product ID;
$product_id = 12345;
// Check if the product is not in the cart.
if( ! $cart->find_product_in_cart( $cart->generate_cart_id( $product_id ) ) ) {
// If not cart then run this code.

$qty = $cart->get_cart_contents_count();
if ( $qty > 1 ) {
$name      = 'Korting meerdere deelnemers';
$amount    = -10;
$taxable   = true;
$tax_class = '';
$cart->add_fee( $name, $amount, $taxable, $tax_class );
}
}
}
}

最新更新