【问题标题】:Checkbox enabling a percentage discount in WooCommerce Checkout for specific category在 WooCommerce Checkout 中为特定类别启用百分比折扣的复选框
【发布时间】:2020-10-27 00:42:01
【问题描述】:

下面的修改代码基于Add a checkout checkbox field that enable a percentage fee in Woocommerce。我已经适应,但希望只针对特定类别,因此当学生在结帐时勾选框,定义他们是学生,它将从他们的总数中扣除 15%,但仅限于特定类别范围 - 即“在线研讨会”。这超出了我的范围,因此希望能得到一些帮助。

// Add a custom checkbox fields after billing fields
add_action( 'woocommerce_after_checkout_billing_form', 'add_custom_checkout_checkbox', 20 );
function add_custom_checkout_checkbox(){

    // Add a custom checkbox field
    woocommerce_form_field( 'student_discount_fee', array(
        'type'  => 'checkbox',
        'label' => __(' Yes, I am a student lawyer studying law'),
        'class' => array( 'form-row-wide' ),
    ), '' );
}

// Remove "(optional)" label on "Student discount checkbox" field
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
    // Only on checkout page for Order notes field
    if( 'student_discount_fee' === $key && is_checkout() ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
    // Only on Checkout
    if( is_checkout() && ! is_wc_endpoint_url() ) :

    if( WC()->session->__isset('enable_fee') )
        WC()->session->__unset('enable_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined') 
            return false;

        $('form.checkout').on('change', 'input[name=student_discount_fee]', function(e){
            var fee = $(this).prop('checked') === true ? '1' : '';

            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'enable_fee',
                    'enable_fee': fee,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                },
            });
        });
    });
    </script>
    <?php
    endif;
}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
function get_enable_fee() {
    if ( isset($_POST['enable_fee']) ) {
        WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
    }
    die();
}

// Add a custom dynamic 15% fee
add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee( $cart ) {
    // Only on checkout
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
        return;

    $percent = -33.33333333333333;

    if( WC()->session->get('enable_fee') )
        $cart->add_fee( __( 'STUDENT LAWYER DISCOUNT', 'woocommerce')." ", ($cart->get_subtotal() * $percent / 100) );
}
// hide coupon field on cart page
function hide_coupon_field_on_cart( $enabled ) {

    if ( is_cart() ) {
        $enabled = false;
    }

    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );

// hide coupon field on checkout page
function hide_coupon_field_on_checkout( $enabled ) {

    if ( is_checkout() ) {
        $enabled = false;
    }

    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_checkout' );

【问题讨论】:

    标签: php jquery ajax woocommerce taxonomy-terms


    【解决方案1】:

    更新 3

    使用以下重新访问的代码和附加的自定义条件函数,该函数检查商品是否仅来自特定产品类别,还可以为您的特定产品类别中的商品提供非折扣小计.

    您必须在该函数中在数组中设置正确的产品类别,并且可以使用术语名称、slug(s) 或 Id(s)。

    小计现在仅针对您的特定产品类别中的折扣商品计算,它是非折扣小计,因此您无需再隐藏优惠券字段。

    当您的特定产品类别中至少有一件商品时,会显示该复选框。

    // Custom conditional function that check for specific product categories (and calculate their subtotal)
    function check_cart_items_for_specific_categories( $type = 'boolean') {
        $categories     = array('online-seminars'); //  <===  Here define your product category (name, slug or Id)
        $category_found = false; // Initializing
        $item_subtotal  = 0; // Initializing
    
        foreach( WC()->cart->get_cart() as $item ) {
            if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) {
                $category_found = true;
                $item_subtotal += $item['line_total'];
            }
        }
    
        if ( $type === 'subtotal' ) {
            return $item_subtotal;
        } else {
            return $category_found;
        }
    }
    
    
    // Add a custom checkbox fields after billing fields
    add_action( 'woocommerce_after_checkout_billing_form', 'add_custom_checkout_checkbox', 20 );
    function add_custom_checkout_checkbox(){
        if( ! check_cart_items_for_specific_categories() ) return; // Exit
    
        // Add a custom checkbox field
        woocommerce_form_field( 'student_discount_fee', array(
            'type'  => 'checkbox',
            'label' => __(' Yes, I am a student lawyer studying law'),
            'class' => array( 'form-row-wide' ),
        ), '' );
    }
    
    // Remove "(optional)" label on "Student discount checkbox" field
    add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
    function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
        // Only on checkout page for Order notes field
        if( 'student_discount_fee' === $key && is_checkout() && check_cart_items_for_specific_categories() ) {
            $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
            $field = str_replace( $optional, '', $field );
        }
        return $field;
    }
    
    // jQuery - Ajax script
    add_action( 'wp_footer', 'checkout_fee_script' );
    function checkout_fee_script() {
        // Only on Checkout
        if( is_checkout() && ! is_wc_endpoint_url() && check_cart_items_for_specific_categories() ) :
    
        if( WC()->session->__isset('enable_fee') )
            WC()->session->__unset('enable_fee')
        ?>
        <script type="text/javascript">
        jQuery( function($){
            if (typeof wc_checkout_params === 'undefined')
                return false;
    
            $('form.checkout').on('change', 'input[name=student_discount_fee]', function() {
                var fee = $(this).prop('checked') === true ? '1' : '';
    
                $.ajax({
                    type: 'POST',
                    url: wc_checkout_params.ajax_url,
                    data: {
                        'action'    : 'enable_fee',
                        'enable_fee': fee,
                    },
                    success: function (result) {
                        $('body').trigger('update_checkout');
                    },
                });
            });
        });
        </script>
        <?php
        endif;
    }
    
    // Get Ajax request and saving to WC session
    add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
    add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
    function get_enable_fee() {
        if ( isset($_POST['enable_fee']) ) {
            WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
        }
        die();
    }
    
    // Add a custom dynamic 15% fee
    add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
    function custom_percentage_fee( $cart ) {
        // Only on checkout
        if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
            return;
    
        if( WC()->session->get('enable_fee') && check_cart_items_for_specific_categories() ) {
            $percentage = -33.33333333333333; // Set the percentage discount (negative float number)
            $subtotal   = check_cart_items_for_specific_categories('subtotal'); // Related items subtotal
            $discount   = $subtotal * $percentage / 100;
    
            $cart->add_fee( strtoupper( __( 'Student lawyer discount', 'woocommerce') ), $discount );
        }
    }
    

    代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 感谢@LoicTheAztec。不过有些不太对劲。只要购物车中有在线研讨会项目,该复选框就必须可见。目前,如果在线研讨会中包含另一个类别项目,则它不再可见。它应该是可见的,但仅从在线研讨会项目中扣除 15%,仅此而已。对不起,如果我不清楚。完成后,我很乐意接受并投票。期待一些 $$ 也为你所有的努力。非常感谢。
    • @Herbivore 代码已更新,现在可以按您的预期完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多