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

开发技术 作者: 2024-06-28 21:55:01
我有非常具体的项目,我需要一些不同的购物车规则.我找不到关于如何实现此目的的插件或任何其他资源. 我有子类别1(即表格)和子类别2(即主席).用户只能从子类别表中添加1个产品,这些产品是强制性的,并且可以从子类别的主席中添加尽可能多的产品. 我需要下一条规则:如果用户还从子类别主席添加了产品,则从子类别表格产品中减去子类别主席产品的总价格.在这种情况下,如果价格将是< 0,然后将价格设为0. 有谁
我有非常具体的项目,我需要一些不同的购物车规则.我找不到关于如何实现此目的的插件或任何其他资源.

我有子类别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

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_35209.html