加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – WooCommerce – 基于子类别的条件购物车计算

发布时间:2020-12-13 16:06:24 所属栏目:PHP教程 来源:网络整理
导读:我有非常具体的项目,我需要一些不同的购物车规则.我找不到关于如何实现此目的的插件或任何其他资源. 我有子类别1(即表格)和子类别2(即主席).用户只能从子类别表中添加1个产品,这些产品是强制性的,并且可以从子类别的主席中添加尽可能多的产品. 我需要下一条
我有非常具体的项目,我需要一些不同的购物车规则.我找不到关于如何实现此目的的插件或任何其他资源.

我有子类别1(即表格)和子类别2(即主席).用户只能从子类别表中添加1个产品,这些产品是强制性的,并且可以从子类别的主席中添加尽可能多的产品.

我需要下一条规则:如果用户还从子类别主席添加了产品,则从子类别表格产品中减去子类别主席产品的总价格.在这种情况下,如果价格将是< 0,然后将价格设为0. 有谁知道如何使用标准的Wordpress Woocommerce做到这一点?

解决方法

这可以做到这一点,根据您的子类别要求和计算在购物车中添加折扣……

代码:

add_action( 'woocommerce_cart_calculate_fees','table_chairs_cart_discount',10,1 );
function table_chairs_cart_discount($cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Initializing variables
    $chairs_total = 0;
    $table_total = 0;
    $discount = 0;

    // Iterating through each cart item
    foreach($cart_object->get_cart() as $item_key => $item):

        $item_line_total = $item["line_total"]; // Item total price (price x quantity)

        // Chairs subcategory items
        if(has_term('chairs','product_cat',$item['product_id']))
            $chairs_total += $item_line_total;

        // Table subcategory items
        if(has_term('table',$item['product_id']))
            $table_total += $item_line_total;

    endforeach;

    // ## CALCULATIONS ##
    if( $table_total <= $chairs_total && $chairs_total > 0 ) 
        $discount -= $table_total;
    elseif ($chairs_total > 0) 
        $discount -= $chairs_total;

    // Adding the discount
    if ($discount != 0)
        $cart_object->add_fee( __( 'Chairs discount','woocommerce' ),$discount,false );
        // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}

代码位于活动子主题(或主题)的function.php文件中.或者也可以在任何插件php文件中.

相关回答:Discount for Certain Category Based on Total Number of Products

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读