Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Woocommerce将折扣应用于购物车';ajax的总价格是多少_Ajax_Wordpress_Woocommerce_Cart_Hook Woocommerce - Fatal编程技术网

Woocommerce将折扣应用于购物车';ajax的总价格是多少

Woocommerce将折扣应用于购物车';ajax的总价格是多少,ajax,wordpress,woocommerce,cart,hook-woocommerce,Ajax,Wordpress,Woocommerce,Cart,Hook Woocommerce,我的目标:使用AJAX在购物车总价上打10%的折扣 上下文:此折扣仅适用于来自给定网站的特定用户。想法是在我添加到购物车页面的输入字段中获取他们的会员编号。使用API,我将检查这个数字并应用折扣或不应用折扣(考虑到进一步解释的问题,我不会在这里详细介绍这个检查部分,只关注问题) 想法: (function($) { $("body").on("click", ".updateCart", function(e) {

我的目标:使用AJAX在购物车总价上打10%的折扣

上下文:此折扣仅适用于来自给定网站的特定用户。想法是在我添加到购物车页面的输入字段中获取他们的会员编号。使用API,我将检查这个数字并应用折扣或不应用折扣(考虑到进一步解释的问题,我不会在这里详细介绍这个检查部分,只关注问题)

想法:

(function($) {
    $("body").on("click", ".updateCart", function(e) {
        e.preventDefault();
        var form = $('#cartAjaxTcs');
        var value = form.serialize();
        $.ajax({
            type:'POST',
            data: {
                action: 'test',
                number: value
            },
            url: ajaxurl,
            success: function(value) {
                jQuery("[name='update_cart']").removeAttr('disabled');
                jQuery("[name='update_cart']").trigger("click");
                console.log(value);
            },
            error:function(){
                console.log('error');
            }
        });
    });
})( jQuery );

<?php

/*
  Plugin Name: discount Plugin
  Description: Apply 10% discount on cart's price
  Author: Aurélien
  Version: 1.0.0
 */

/**
* Check if WooCommerce is active
**/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

    class Discount_Plugin{

        public static function init() {

            add_action('wp_enqueue_scripts',  __CLASS__ .'::callback_for_setting_up_scripts');

            //Add input field
            add_action('woocommerce_cart_collaterals', __CLASS__.'::order_comments_custom_cart_field');

        }

        public static function callback_for_setting_up_scripts() {
            $path = '/wp-content/plugins/discount-plugin/assets/css/style.css';
            wp_register_style( 'discountStyle', $path );
            wp_enqueue_style( 'discountStyle' );
            wp_enqueue_script( 'ajax-script', plugins_url( 'assets/js/discount-plugin.js', __FILE__ ), array('jquery'), '1.0', true );
            wp_localize_script( 'ajax-script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
        }

        public static function order_comments_custom_cart_field() {
            ?>
            <form id="cartAjaxTcs" class="discount_input_wrapper" method="post" action="/wp-admin/admin-post.php">
                <div class="discount_form_field">
                    <input type="text" name="number" id="number" placeholder="<?php echo 'My number, ie : 4GG524G42';?>">
                    <label for="number"><?php echo 'Membership number';?></label>
                </div>
                <button class="updateCart" type="submit"><?php echo 'Update cart';?></button>
            </form>
            <?php

        }

 

    Discount_Plugin::init();
    add_action( 'wp_ajax_test', 'test' );
    add_action( 'wp_ajax_nopriv_test', 'test' );

    function test()
    {
      //Solution 1 or solution 2
    }

}
  • 创建一个插件,该插件将在购物车页面中添加一个带有验证按钮的输入字段
  • 单击按钮时进行AJAX调用
  • 如果用户成员号是好的,则应用折扣(我不会在这里处理API检查,因为这不是问题)
  • 问题:所以我使用AJAX验证这个数字,然后对购物车的总价格应用10%的折扣。问题是我找不到如何更新总数

    我的JS:

    (function($) {
        $("body").on("click", ".updateCart", function(e) {
            e.preventDefault();
            var form = $('#cartAjaxTcs');
            var value = form.serialize();
            $.ajax({
                type:'POST',
                data: {
                    action: 'test',
                    number: value
                },
                url: ajaxurl,
                success: function(value) {
                    jQuery("[name='update_cart']").removeAttr('disabled');
                    jQuery("[name='update_cart']").trigger("click");
                    console.log(value);
                },
                error:function(){
                    console.log('error');
                }
            });
        });
    })( jQuery );
    
    
    <?php
    
    /*
      Plugin Name: discount Plugin
      Description: Apply 10% discount on cart's price
      Author: Aurélien
      Version: 1.0.0
     */
    
    /**
    * Check if WooCommerce is active
    **/
    if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
        class Discount_Plugin{
    
            public static function init() {
    
                add_action('wp_enqueue_scripts',  __CLASS__ .'::callback_for_setting_up_scripts');
    
                //Add input field
                add_action('woocommerce_cart_collaterals', __CLASS__.'::order_comments_custom_cart_field');
    
            }
    
            public static function callback_for_setting_up_scripts() {
                $path = '/wp-content/plugins/discount-plugin/assets/css/style.css';
                wp_register_style( 'discountStyle', $path );
                wp_enqueue_style( 'discountStyle' );
                wp_enqueue_script( 'ajax-script', plugins_url( 'assets/js/discount-plugin.js', __FILE__ ), array('jquery'), '1.0', true );
                wp_localize_script( 'ajax-script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
            }
    
            public static function order_comments_custom_cart_field() {
                ?>
                <form id="cartAjaxTcs" class="discount_input_wrapper" method="post" action="/wp-admin/admin-post.php">
                    <div class="discount_form_field">
                        <input type="text" name="number" id="number" placeholder="<?php echo 'My number, ie : 4GG524G42';?>">
                        <label for="number"><?php echo 'Membership number';?></label>
                    </div>
                    <button class="updateCart" type="submit"><?php echo 'Update cart';?></button>
                </form>
                <?php
    
            }
    
     
    
        Discount_Plugin::init();
        add_action( 'wp_ajax_test', 'test' );
        add_action( 'wp_ajax_nopriv_test', 'test' );
    
        function test()
        {
          //Solution 1 or solution 2
        }
    
    }
    
    我的PHP:

    (function($) {
        $("body").on("click", ".updateCart", function(e) {
            e.preventDefault();
            var form = $('#cartAjaxTcs');
            var value = form.serialize();
            $.ajax({
                type:'POST',
                data: {
                    action: 'test',
                    number: value
                },
                url: ajaxurl,
                success: function(value) {
                    jQuery("[name='update_cart']").removeAttr('disabled');
                    jQuery("[name='update_cart']").trigger("click");
                    console.log(value);
                },
                error:function(){
                    console.log('error');
                }
            });
        });
    })( jQuery );
    
    
    <?php
    
    /*
      Plugin Name: discount Plugin
      Description: Apply 10% discount on cart's price
      Author: Aurélien
      Version: 1.0.0
     */
    
    /**
    * Check if WooCommerce is active
    **/
    if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
        class Discount_Plugin{
    
            public static function init() {
    
                add_action('wp_enqueue_scripts',  __CLASS__ .'::callback_for_setting_up_scripts');
    
                //Add input field
                add_action('woocommerce_cart_collaterals', __CLASS__.'::order_comments_custom_cart_field');
    
            }
    
            public static function callback_for_setting_up_scripts() {
                $path = '/wp-content/plugins/discount-plugin/assets/css/style.css';
                wp_register_style( 'discountStyle', $path );
                wp_enqueue_style( 'discountStyle' );
                wp_enqueue_script( 'ajax-script', plugins_url( 'assets/js/discount-plugin.js', __FILE__ ), array('jquery'), '1.0', true );
                wp_localize_script( 'ajax-script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
            }
    
            public static function order_comments_custom_cart_field() {
                ?>
                <form id="cartAjaxTcs" class="discount_input_wrapper" method="post" action="/wp-admin/admin-post.php">
                    <div class="discount_form_field">
                        <input type="text" name="number" id="number" placeholder="<?php echo 'My number, ie : 4GG524G42';?>">
                        <label for="number"><?php echo 'Membership number';?></label>
                    </div>
                    <button class="updateCart" type="submit"><?php echo 'Update cart';?></button>
                </form>
                <?php
    
            }
    
     
    
        Discount_Plugin::init();
        add_action( 'wp_ajax_test', 'test' );
        add_action( 'wp_ajax_nopriv_test', 'test' );
    
        function test()
        {
          //Solution 1 or solution 2
        }
    
    }
    
    我的第二个解决方案: 我试图触发“更新购物车”按钮(已经出现在页面上),并使用woocommerce\u-before\u-calculate\u-totals钩子更新价格,但它甚至没有被调用

    显然,在我的AJAX操作函数中没有执行任何钩子或过滤器。我已经用一个简单的过滤器进行了测试,将一个类添加到主体中,它在我的动作函数内部不起作用,但在外部却可以完美地工作。我放置了一些标志,以查看我的函数是否由AJAX调用,并且它是

    //This works well! If I put the same filter in my 'test' function it doesn't work
    add_filter( 'body_class', function( $classes ) {
        return array_merge( $classes, array( 'test-class' ) );
    } );
    
    function test()
    {
        //This is displayed in console
        echo'test-init';
    
        if (!DOING_AJAX){
            return;
        }
        
        //This does't work
        add_filter( 'body_class', function( $classes ) {
          return array_merge( $classes, array( 'test-class2' ) );
        } );
        
        //The callback function isn't called
        add_action( 'woocommerce_before_calculate_totals', 'update_price' );
    
        //This is displayed in console
        echo 'test';
    
        wp_die();
    }
    
    //Not called
    function update_price(){
        echo 'update';
    }
    

    编辑:

    (function($) {
        $("body").on("click", ".updateCart", function(e) {
            e.preventDefault();
            var form = $('#cartAjaxTcs');
            var value = form.serialize();
            $.ajax({
                type:'POST',
                data: {
                    action: 'test',
                    number: value
                },
                url: ajaxurl,
                success: function(value) {
                    jQuery("[name='update_cart']").removeAttr('disabled');
                    jQuery("[name='update_cart']").trigger("click");
                    console.log(value);
                },
                error:function(){
                    console.log('error');
                }
            });
        });
    })( jQuery );
    
    
    <?php
    
    /*
      Plugin Name: discount Plugin
      Description: Apply 10% discount on cart's price
      Author: Aurélien
      Version: 1.0.0
     */
    
    /**
    * Check if WooCommerce is active
    **/
    if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
        class Discount_Plugin{
    
            public static function init() {
    
                add_action('wp_enqueue_scripts',  __CLASS__ .'::callback_for_setting_up_scripts');
    
                //Add input field
                add_action('woocommerce_cart_collaterals', __CLASS__.'::order_comments_custom_cart_field');
    
            }
    
            public static function callback_for_setting_up_scripts() {
                $path = '/wp-content/plugins/discount-plugin/assets/css/style.css';
                wp_register_style( 'discountStyle', $path );
                wp_enqueue_style( 'discountStyle' );
                wp_enqueue_script( 'ajax-script', plugins_url( 'assets/js/discount-plugin.js', __FILE__ ), array('jquery'), '1.0', true );
                wp_localize_script( 'ajax-script', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
            }
    
            public static function order_comments_custom_cart_field() {
                ?>
                <form id="cartAjaxTcs" class="discount_input_wrapper" method="post" action="/wp-admin/admin-post.php">
                    <div class="discount_form_field">
                        <input type="text" name="number" id="number" placeholder="<?php echo 'My number, ie : 4GG524G42';?>">
                        <label for="number"><?php echo 'Membership number';?></label>
                    </div>
                    <button class="updateCart" type="submit"><?php echo 'Update cart';?></button>
                </form>
                <?php
    
            }
    
     
    
        Discount_Plugin::init();
        add_action( 'wp_ajax_test', 'test' );
        add_action( 'wp_ajax_nopriv_test', 'test' );
    
        function test()
        {
          //Solution 1 or solution 2
        }
    
    }
    
    我重新编写了我的解释,通过附加代码使它们更易于理解:

    以下是一些使用
    woocommerce\u cart\u calculate\u fees
    hook的负费用尝试:

    如果我在AJAX操作函数之外使用add\u操作,那么woocommerce\u cart\u calculate\u fees hook的回调函数将非常有效,如下所示:

    add_action( 'wp_ajax_test', 'test' );
    add_action( 'wp_ajax_nopriv_test', 'test' );
    
    add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
    function woocommerce_custom_surcharge() {
        global $woocommerce;
    
        if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
            return;
    
        $percentage = 0.1;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
        $woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
    
    }
    
    function test(){
       
       //My AJAX action function
    
    }
    
    add_action( 'wp_ajax_test', 'test' );
    add_action( 'wp_ajax_nopriv_test', 'test' );
    
    function woocommerce_custom_surcharge() {
        global $woocommerce;
    
        if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
            return;
    
        $percentage = 0.1;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
        $woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
    
    }
    
    //My AJAX action function
    function test(){
    
       echo 'test1'; //flag 1
       add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
       echo 'test2'; //flag 2
    }
    
    所以这项工作,应用了否定费,但当页面加载时,这不是我想要的,因为我想在触发更新购物车按钮时应用否定费,所以想法是将add_操作集成到我的AJAX操作函数中,如下所示:

    add_action( 'wp_ajax_test', 'test' );
    add_action( 'wp_ajax_nopriv_test', 'test' );
    
    add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
    function woocommerce_custom_surcharge() {
        global $woocommerce;
    
        if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
            return;
    
        $percentage = 0.1;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
        $woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
    
    }
    
    function test(){
       
       //My AJAX action function
    
    }
    
    add_action( 'wp_ajax_test', 'test' );
    add_action( 'wp_ajax_nopriv_test', 'test' );
    
    function woocommerce_custom_surcharge() {
        global $woocommerce;
    
        if ( ( is_admin() && ! defined( 'DOING_AJAX' )))
            return;
    
        $percentage = 0.1;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
        $woocommerce->cart->add_fee( 'discount', -$surcharge, true, '' );
    
    }
    
    //My AJAX action function
    function test(){
    
       echo 'test1'; //flag 1
       add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
       echo 'test2'; //flag 2
    }
    

    根本不调用回调函数woocommerce\u custom\u。两个my标志都显示在chrome控制台中,因此这意味着正确调用了my action函数。因此,我的问题是:如何使此添加操作在我的操作函数中工作?

    您错过了WC会话变量用于设置一些数据并在折扣函数中使用它的用法…下面的第一个函数处理您的设置,它在其他函数中随处加载

    // Settings
    function get_membership_settings(){
        $discount_percentage = 1; // the discount percentage: 1% here
    
        return array(
            'percentage'       => $discount_percentage,
            'field_key'        => 'membership_number', // Field "name" key (or id)
            'field_type'       => 'text',
            'field_label'      =>  __('Membership number', 'woocommerce'),
            'button_text'      =>  __('Apply membership number', 'woocommerce'),
            'discount_text'    =>  sprintf( __('Membership discount%s', 'woocommerce'), ' ('.$discount_percentage.' %)' ), // for negative fee
            'valid_message'    => __('Number is valid (text message).', 'woocommerce'),
            'unvalid_message'  => __('Number not valid (text message).', 'woocommerce'),
            'empty_field_text' => __('Please enter your membership number.', 'woocommerce'),
         );
    }
    
    // Settings + Membership number
    function get_membership_data(){
        $settings      = get_membership_settings();// Load settings
        $field_key     = $settings['field_key']; // The field Id
    
        $user_value    = get_user_meta( get_current_user_id(), $field_key, true ); // Get "membership number" from user data
        $session_value = WC()->session->get($field_key); // Get "membership number" from session variable
    
        // Set "membership number" in the array
        $settings['field_value'] = empty($session_value) ? $user_value : $session_value;
    
        return $settings;
    }
    
    购物车上显示的字段(参见末尾的屏幕截图):

    折扣部分: 有多种打折方式(这里有两种,使用不同的挂钩):

    1.基于折扣的购物车小计+运费(负费用): 2.购物车商品价格折扣: 所有代码都进入活动子主题(或活动主题)的functions.php文件中。测试和工作


    类似的线程:


    您的解释、详细信息和提供的代码不太清楚……如果您不想使用优惠券,您可以使用负的购物车费用来获得10%的折扣。感谢您的回答@LoicTheAztec,我已经修改了回复。我还更新了我的代码和描述。我希望它现在可以测试。谢谢你的回答!非常感谢你的帮助!太完美了!但我有一个问题,“woocommerce\u cart\u calculate\u fees”钩子是如何触发的?这是由于WC()->会话更新造成的吗?(考虑使用您的第一折扣解决方案)我理解,但是这个Ajax部分没有加载页面,那么是什么触发了这个钩子呢?当页面正常加载时,我知道它是由加载和一些购物车事件触发的,但当它未加载时,我想知道它是如何触发的(仅供我自己理解),我代码中的Ajax部分只是设置了一个WC会话变量并返回对javascript的响应……在该响应中,我(Ajax)使用
    刷新购物车页面$(document.body).trigger(“added_to_cart”)
    …它适用于具有店面主题的上次WooCommerce版本。hook
    WooCommerce_cart_calculate_fees
    WC_cart
    方法
    calculate_fees()
    触发。请参阅:非常感谢您所做的一切!