[英]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.