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

qltillow  于 2022-11-21  发布在  PHP
关注(0)|答案(1)|浏览(143)

我们运行了这个函数,当产品的数量〉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 );
         }
        }
    }
}

`
我做错了什么?
我尝试添加一个检查,如果产品是在购物车。如果真的,什么也不做。如果假的,运行功能。

4nkexdtk

4nkexdtk1#

你在函数外编写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 );
            }
        }
    }
}

相关问题