我正在尝试编写一个脚本,允许用户只添加每个类别的单个产品。
我的方法背后是: -
这样的事情可能吗?
我不确定从哪里开始,我们将非常感谢任何帮助。
我知道我可以使用以下标记触发jQuery事件: -
<input type='button'
id="button-switch"
value='Hide/Show Redlines' / >
<script>(function () {
'use strict';
function init() {
var el = document.getElementById('deconstructed');
var button = document.getElementById('button-switch');
button.onclick = function () {
el.id == 'deconstructed' ? (el.id = 't-b', el.src = '_images/clean_image.png', el.alt = 'my t-b',
button.value = 't-b'
)
: (el.id = 'deconstructed', el.src = '_images/labeled_image.png', el.alt = 'my deconstructed',
button.value = ' Hide/Show Redlines');
}
}
window.addEventListener('load', init, false);
})();
</script>
< !--PLACE * LABELED * ONE MORE TIME HERE -- >
< div > < img id = "deconstructed" src = "_images/labeled_image.png" alt = "my deconstructed" > < / div >
但这就是我被困住的地方。
提前致谢。
答案 0 :(得分:0)
我使用以下内容来实现我想要的: -
<?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] );
}
}
}
}