Dynamic discount using AJAX and Fee API in Woocommerce checkout page

随声附和 提交于 2021-02-19 04:39:07

问题


I have put a select box in the checkout page like this.

function rx_wc_reward_points_check() {

    $reward_points = '<select class="rx-rewad-points" id="rx-redemption-points">
        <option value="1250">$25.00 Off (1250 Points) </option>
        <option value="2500">$50.00 Off (2500 Points) </option>
        <option value="5000">$100.00 Off (5000 Points) </option>
        <option value="7000">$150.00 Off (7000 Points) </option>
    </select>';
    $reward_points .= '<a class="button alt" name="rx_reward_points_btn" id="rx_reward_points" value="Apply" data-value="Reward Points">Apply Now</a>';
    echo $reward_points;
}
add_action( 'woocommerce_checkout_after_customer_details', 'rx_wc_reward_points_check', 10, 0 ); 

After that i have added this to the function file for

function rx_wc_deduct_reward() {
    global $woocommerce;
    $reward_value = $_POST['rewardpoints'];
    WC()->cart->add_fee( 'Fee', -$reward_value );

    echo 'success';
    exit;
}
add_action( 'wp_ajax_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
add_action( 'wp_ajax_nopriv_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );

This is using for the ajax part

jQuery(document).ready( function() {
    jQuery('#rx_reward_points').on('click', function() {
        var selectedrewad = jQuery( "#rx-redemption-points option:selected" ).val();
        jQuery.ajax({
         type : "post",
         url : ajax_var.ajaxurl,
         data : { action: "rx_wc_deduct_reward", rewardpoints : selectedrewad },
         success: function(response) {
            console.log(response)
            if(response == "success") {
               console.log('done');
            }
            else {
               console.log("Your vote could not be added")
            }
         }
        });
    })
})

But it is not working. I have done some mistake in the "rx_wc_deduct_reward" function. I cant figure out how to do this.

Any help is appreciated.


回答1:


You need to make it slight different to get it work as you get some errors and missing parts:

// Displaying a select field and a submit button in checkout page
add_action( 'woocommerce_checkout_after_customer_details', 'rx_wc_reward_points_check', 10, 0 );
function rx_wc_reward_points_check() {

    echo '<select class="rx-rewad-points" id="rx-redemption-points">
        <option value="25">' . __("$25.00 Off (1250 Points)", "woocommerce" ) . '</option>
        <option value="50">' . __("$50.00 Off (2500 Points)", "woocommerce" ) . '</option>
        <option value="100">' . __("$100.00 Off (5000 Points)", "woocommerce" ) . '</option>
        <option value="150">' . __("$150.00 Off (7000 Points)", "woocommerce" ) . '</option>
    </select>
    <a class="button alt" name="rx_reward_points_btn" id="rx_reward_points" value="Apply" data-value="Reward Points">Apply Now</a>';
}

// jQuery - Ajax script
add_action( 'wp_footer', 'rx_wc_reward_points_script' );
function rx_wc_reward_points_script() {
    // Only checkout page
    if ( ! is_checkout() ) return;
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('#rx_reward_points').on('click', function() {
            $.ajax({
                type: "post",
                url:  wc_checkout_params.ajax_url,
                data: {
                     'action' : 'rx_wc_deduct_reward',
                     'rewardpoints' : $("#rx-redemption-points").val()
                },
                success: function(response) {
                    $('body').trigger('update_checkout');
                    console.log('response: '+response); // just for testing | TO BE REMOVED
                },
                error: function(error){
                    console.log('error: '+error); // just for testing | TO BE REMOVED
                }
            });
        })
    })
    </script>
    <?php
}

// Wordpress Ajax code (set ajax data in Woocommerce session)
add_action( 'wp_ajax_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
add_action( 'wp_ajax_nopriv_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
function rx_wc_deduct_reward() {
    if( isset($_POST['rewardpoints']) ){
        WC()->session->set( 'custom_fee', esc_attr( $_POST['rewardpoints'] ) );
        echo true;
    }
    exit();
}

// Add a custom dynamic discount based on reward points
add_action( 'woocommerce_cart_calculate_fees', 'rx_rewardpoints_discount', 20, 1 );
function rx_rewardpoints_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Only for targeted shipping method
    if (  WC()->session->__isset( 'custom_fee' ) )
        $discount = (float) WC()->session->get( 'custom_fee' );

    if( isset($discount) && $discount > 0 )
        $cart->add_fee( __( 'Reward discount', 'woocommerce' ), -$discount );
}

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



来源:https://stackoverflow.com/questions/51648535/dynamic-discount-using-ajax-and-fee-api-in-woocommerce-checkout-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!