Php Woocommerce仅添加1个基于类别的产品

Php Woocommerce仅添加1个基于类别的产品,php,jquery,ajax,wordpress,woocommerce,Php,Jquery,Ajax,Wordpress,Woocommerce,我正在尝试编写一个脚本,允许用户只添加每个类别中的单个产品 我的方法如下:- 用户单击以添加项目 如果项目在具有相同数量结束脚本的篮子中 如果数量不同,则使用新数量更新 如果产品不在篮子中,检查篮子中是否有属于同一类别的其他项目 如果项目存在,请删除属于相同类别名称的项目 添加新项目 这样的事情可能吗 我不知道从哪里开始,任何帮助都将不胜感激 我知道我可以使用以下标记触发jQuery事件:- jQuery('button').on('added_to_cart',function() {

我正在尝试编写一个脚本,允许用户只添加每个类别中的单个产品

我的方法如下:-

  • 用户单击以添加项目
  • 如果项目在具有相同数量结束脚本的篮子中
  • 如果数量不同,则使用新数量更新
  • 如果产品不在篮子中,检查篮子中是否有属于同一类别的其他项目
  • 如果项目存在,请删除属于相同类别名称的项目
  • 添加新项目
这样的事情可能吗

我不知道从哪里开始,任何帮助都将不胜感激

我知道我可以使用以下标记触发jQuery事件:-

jQuery('button').on('added_to_cart',function() {
    jQuery.post("?wc-ajax=add_to_cart",
    {
        product_id: jQuery(this).attr('data-product_id'),
        quantity: jQuery(this).attr('data-quantity'),
    },
    function(data,status){
    });
});
但这就是我被卡住的地方


提前感谢。

我用以下方法实现了我想要的:-

<?php

if ( ! is_admin() ) add_action( 'woocommerce_add_to_cart', 'add_product_to_cart', 1 );
function add_product_to_cart() {

    global $woocommerce;

    // Getting posted product information
    $post_product_id = $_POST['product_id'];
    $post_product_qty = $_POST['quantity'];
    $post_product_cats = wp_get_post_terms( $post_product_id , 'product_cat' );
    $post_product_cat = $post_product_cats[0]->name;

    // Getting cart items
    $items = $woocommerce->cart->get_cart();

    foreach($items as $item => $values) {

        // Getting cart product information
        $_product = $values['data']->post;
        $_product_id = $_product->ID;
        $_product_cats = wp_get_post_terms( $_product_id , 'product_cat' );
        $_product_cat = $_product_cats[0]->name;
        $_product_qty = $values['quantity'];
        $prod_unique_id = WC()->cart->generate_cart_id( $_product_id );

        // Check if product categories are the same
        if($post_product_cat == $_product_cat){
            // Check if the product ID's are the same
            if($post_product_id == $_product_id){
                // Check if quantities are different
                if($post_product_qty != $_product_qty){
                    // Update quantities if they are different
                    WC()->cart->set_quantity($prod_unique_id, $post_product_qty);
                }
            } else {
                // Remove items that are in the same category
                unset( WC()->cart->cart_contents[$prod_unique_id] );
            }
        }

    } 

}

我建议您通过filter@helgatheviking我试图使用它,但它将产品添加到购物车,然后将我推到产品页面。