如何为“woocommerce_add_to_cart"添加过滤器或挂钩; [英] How to add filter or hook for "woocommerce_add_to_cart"

查看:29
本文介绍了如何为“woocommerce_add_to_cart"添加过滤器或挂钩;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时添加两个产品到购物车,一个是原始(当前)产品,第二个来自下拉列表

I want add to cart two product at the same time, one is original (current) product and second is from drop-down list

add_action('woocommerce_add_to_cart', 'custome_add_to_cart');
$cnt=2
function custome_add_to_cart() {
    global $woocommerce;
      $cnt = $cnt + 1;
      echo $cnt."X";
      echo $p_id=$_POST['assessories'];
    $woocommerce->cart->add_to_cart($p_id, 1);

}

输出:-正如您在下面的输出图像中看到的,它在购物车中多次添加相同的下拉项目,但我只想将 1 个数量添加到购物车.似乎 add_to_cart 函数运行了很多次.我应该怎么做或如何通过将第二个下拉产品作为参数添加到购物车功能来添加过滤器?所以我也可以将这个产品添加到购物车中.

Output:- As you can see in output image below , it adding same drop-down item many time in cart but i want only 1 quantity to add to cart. it seems that add_to_cart function run many times. What should i do or how to add filter with passing second drop-down product as parameter to add to cart function ? so i can add this product also in cart.

推荐答案

这应该有效:

add_action('woocommerce_add_to_cart', 'custome_add_to_cart');
function custome_add_to_cart() {
    global $woocommerce;

    $product_id = $_POST['assessories'];

    $found = false;

    //check if product already in cart
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->id == $product_id )
                $found = true;
        }
        // if product not found, add it
        if ( ! $found )
            WC()->cart->add_to_cart( $product_id );
    } else {
        // if no products in cart, add it
        WC()->cart->add_to_cart( $product_id );
    }
}

基于以下来源:https://docs.woothemes.com/document/automatically-add-product-to-cart-on-visit/

这篇关于如何为“woocommerce_add_to_cart"添加过滤器或挂钩;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆