WooCommerce-产品档案中的添加到购物车功能,单个产品页面和购物车是否不同?

时间:2020-08-26 09:10:40

标签: php wordpress woocommerce

我现在要离开我的键盘,脸上带着微笑,因为最后,我完成了我想在网站上进行的操作。 但不,有什么不对。

我只想将购物车限制为10种产品,并显示一个弹出对话框 在Elementor中创建并显示一条消息,指出他们不能添加超过10个 产品。

因此,我在woocommerce_add_to_cart中添加了带有以下代码的functions.php操作。

function woocommerce_ajax_add_to_cart(){
    ob_start();
    if ( ! isset( $_POST['product_id'] ) ) {
        return;
    }
    $found = false;
        
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) { //check if product already in cart
        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->id == $product_id )
                $found = true;
        }
        if ( ! $found ){ // if product not found, add it
            $cart_items_count = WC()->cart->get_cart_contents_count();
            $total_count = $cart_items_count + $quantity;
            if ( $cart_items_count > 10 || $total_count > 10 ) {
                $data = array( 'error' => true, 'is_full_cart' => true, 'datas' => $cart_items_count );
                wp_send_json( $data );
            }else{
                WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
            }
        }
    } else {
        WC()->cart->add_to_cart(  $product_id, $quantity, $variation_id, $variation ); // if no products in cart, add it
    }
}
add_action('woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');

//Create a new copy of add-to-cart.js and add the elementor popup
function child_enqueue_parent_style() {
    wp_dequeue_script('woocommerce-ajax-add-to-cart');
    wp_enqueue_script('woocommerce-ajax-add-to-cart', get_stylesheet_directory_uri().'/js/add-to-cart.js', array('jquery'));

}
add_action( 'wp_enqueue_scripts', 'child_enqueue_parent_style' );

然后在add-to-cart.js

....
e.data.addToCartHandler.addRequest({
    type: 'POST',
    url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
    data: data,
    success: function( response ) {
        if ( ! response ) {
            return;
        }

       //show elementor popup full cart
       if ( response.error && response.is_full_cart ) {
            elementorProFrontend.modules.popup.showPopup( { id: 2409 } );
            return;
        }
                    .....
    },
    dataType: 'json'
});

好吧,这仅适用于产品归档中的内容,而不适用于单个产品页面上,或者当您在购物车页面中尝试更新产品数量时。

这是否意味着这三个功能不同?

0 个答案:

没有答案