簡體   English   中英

Woocommerce僅添加1個基於類別的產品

[英]Woocommerce Add only 1 product based on category

我正在嘗試編寫一個腳本,該腳本只允許用戶從每個類別中添加一個產品。

我背后的方法是:

  • 用戶點擊添加項目
  • 如果項目在籃子中且帶有相同數量的結束腳本
  • 如果數量不同,則更新新數量
  • 如果產品不在籃子中,請檢查籃子中是否有其他物品屬於同一類別
  • 如果存在項目,則刪除屬於相同類別名稱的項目
  • 新增項目

這樣的事情可能嗎?

我不確定從哪里開始,任何幫助將不勝感激。

我知道我可以使用以下標記觸發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] );
            }
        }

    } 

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM