在 Woocommerce 结帐页面中将产品添加到购物车的复选框字段 [英] Checkbox field that add to cart a product in Woocommerce checkout page

查看:23
本文介绍了在 Woocommerce 结帐页面中将产品添加到购物车的复选框字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Woocommerce 结帐部分,我尝试添加一个复选框来添加其他产品.

In Woocommerce checkout section, I am trying to add a checkbox that adds an additional product.

我有一段工作代码,可以在点击复选框时添加费用并更新购物车,但我希望它添加产品而不是附加费:

I have a working piece of code that adds a fee and updates the cart on click of a checkbox, but I want it to add a product instead of a surcharge fee:

function cart_custom_fee( $cart ) {

    if( !$_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );   
    } else {
        $post_data = $_POST;
    }

    if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name
        WC()->cart->add_fee('Test Item', 35);
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'cart_custom_fee' );

这是复选框的代码

<script>
             jQuery(document).ready(function(){
                   jQuery('#cp-checkbox').click(function() {
                      jQuery('body').trigger('update_checkout'); 
                   });
                });
</script>

代码有效......

现在,我尝试更改代码以添加产品:

Now, I tried changing the code to add a product instead:

function add_item_checkout( $cart ) {

    if( !$_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );   
    } else {
        $post_data = $_POST;
    }

    if( isset( $post_data['add_test_item'] ) ) { // This is the checkbox name
        WC()->cart->add_to_cart( 123 ); // 123 is the product ID
    }
}
add_action( 'woocommerce_calculate_totals', 'add_item_checkout' );

但是没有用.任何帮助将不胜感激.

But it didn't work. Any help will be appreciated.

推荐答案

更新 (与您的评论相关).

这只能使用 Javascript (jQuery) 和 Ajax 来完成,因为它是一个客户端事件,并且在结帐字段上执行操作时不会提交任何内容.

This can only be done with Javascript (jQuery) and Ajax as it's a client side event and nothing is submitted when making an action on a checkout field.

选中此复选框后,特定产品将添加到购物车,刷新结帐订单审核数据.如果客户取消选中该复选框,它将删除特定产品,刷新结帐订单审核数据.

When this checkbox will be checked, a specific product will be added to cart refreshing the checkout order review data. If the checkbox is unchecked by the customer, it will remove the specific product, refreshing the checkout order review data.

更新更改:我更改了付款选项下的复选框,并稍微更改了 jQuery 代码,以处理复选框值,因为它现在也刷新了 Ajax.

Update changes: I have changed the checkbox under payment options and lightly changed the jQuery code, to handle the checkbox value, as it's now Ajax refreshed too.

代码:

// Display a custom checkout field
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' );
function custom_checkbox_checkout_field() {
    $value = WC()->session->get('add_a_product');

    woocommerce_form_field( 'cb_add_product', array(
        'type'          => 'checkbox',
        'label'         => '&nbsp;&nbsp;' . __('Add a demo product to your order'),
        'class'         => array('form-row-wide'),
    ), $value == 'yes' ? true : false );
}


// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_custom_jquery_script' );
function checkout_custom_jquery_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Remove custom WC session variables on load
    if( WC()->session->get('add_a_product') ){
        WC()->session->__unset('add_a_product');
    }
    if( WC()->session->get('product_added_key') ){
        WC()->session->__unset('product_added_key');
    }
    // jQuery Ajax code
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('form.checkout').on( 'change', '#cb_add_product', function(){
            var value = $(this).prop('checked') === true ? 'yes' : 'no';

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

// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' );
add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' );
function checkout_ajax_add_a_product() {
    if ( isset($_POST['add_a_product']) ){
        WC()->session->set('add_a_product', esc_attr($_POST['add_a_product']));
        echo $_POST['add_a_product'];
    }
    die();
}

// Add remove free product
add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' );
function adding_removing_specific_product( $cart ) {
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE the specific Product ID
    $product_id = 53;

    if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') )
    {
        $cart_item_key = $cart->add_to_cart( $product_id );
        WC()->session->set('product_added_key', $cart_item_key);
    }
    elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') )
    {
        $cart_item_key = WC()->session->get('product_added_key');
        $cart->remove_cart_item( $cart_item_key );
        WC()->session->__unset('product_added_key');
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中.经过测试和工作.

Code goes in function.php file of your active child theme (or active theme). Tested and work.

  1. 付款方式下的订单项和复选框自定义字段

  1. 启用复选框后,产品将添加并显示在订单项中:

这篇关于在 Woocommerce 结帐页面中将产品添加到购物车的复选框字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆