问题描述
经过长时间的查找,我找不到任何正确的代码,如何为购物车订单项应用优惠券。假设客户添加了一些产品数量 10,我选择的优惠券应该用于该产品。如果他添加了另一个数量超过 10 的产品,则应为该产品再次申请相同的优惠券。 这里有什么帮助吗? 我能够找到类似的东西,但这仅适用于特定的产品 ID,如何更新此代码以浏览每个购物车产品、检查它们的数量并为数量为 10 或更多的产品应用优惠券有什么帮助吗?
类似代码但仅适用于特定产品的参考:
Conditionally apply coupons automatically for specific Product IDs and quantities
图片示例:
解决方法
尝试为下面的问题创建自定义解决方案。并以某种方式做到了,不确定这是否是正确和好的选择,但它至少对我来说完全符合我的需要。这会为商店中的每个产品创建一个单独的优惠券(如果添加了新产品,它也会为其创建一个独特的优惠券)。如果购物车中的产品数量为 10 个或更多,则每个购物车订单项都会自动应用优惠券。它为该产品提供 10% 的折扣。按照下面的代码,也许对某人有用,因为我在任何地方都找不到任何插件或代码可以像这样工作......
$args = array(
'posts_per_page' => -1,'orderby' => 'title','order' => 'asc','post_type' => 'shop_coupon','post_status' => 'publish',);
$all_coupons = get_posts( $args );
// Loop through the available coupons
foreach ( $all_coupons as $coupon ) {
// Get the name for each coupon and add to the previously created array
$coupon_name = $coupon->post_title;
}
foreach ($all_coupons as $coupon) {
$coupons_array[] = $coupon->post_title;
}
$all_ids = get_posts( array(
'post_type' => 'product','numberposts' => -1,'post_status' => 'publish','fields' => 'ids',) );
foreach ( $all_ids as $id ) {
$product_id_array[] = $id;
}
// Get values from arr2 and arr1 unique
$output = array_merge(array_diff($coupons_array,$product_id_array),array_diff($product_id_array,$coupons_array));
function coupon_exists($coupon_code) {
global $wpdb;
$sql = $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_name = '%s'",$coupon_code );
$coupon_codes = $wpdb->get_results($sql);
if (count($coupon_codes)> 0) {
return true;
}
else {
return false;
}
}
foreach ($output as $o) {
if (is_numeric($o)) {
if (!coupon_exists($o)) {
generate_coupon($o);
}
}
}
function generate_coupon($coupon_code){
$coupon = new WC_Coupon();
$coupon->set_code($coupon_code);
//the coupon discount type can be 'fixed_cart','percent' or 'fixed_product',defaults to 'fixed_cart'
$coupon->set_discount_type('percent_product');
//the discount amount,defaults to zero
$coupon->set_amount(10);
$coupon->set_individual_use(false);
$coupon->set_product_ids(array($coupon_code));
//save the coupon
$coupon->save();
return $coupon_code;
}
add_action( 'woocommerce_before_cart','conditional_auto_add_coupons' );
function conditional_auto_add_coupons() {
$all_ids = get_posts( array(
'post_type' => 'product',) );
if ( !WC()->cart->is_empty() ){
// First cart loop: Counting number of subactegory items in cart
foreach ( $all_ids as $id ){
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $id == $cart_item['data']->id ){
if( 10 <= $cart_item['quantity'] ){
WC()->cart->add_discount( $id );
//wc_add_notice( __( 'Discount of <strong>10%</strong> for quantity.','theme_domain' ),'success' );
}else{
WC()->cart->remove_coupon( $id );
//wc_add_notice( __( 'Discount of <strong>10%</strong> due to low quantity removed.','success' );}
}
}
}
}
}
}