【问题标题】:Get WooCommerce cart subtotal in Javascript在 Javascript 中获取 WooCommerce 购物车小计
【发布时间】:2018-03-07 02:34:02
【问题描述】:

我已经设置了一些代码来调整 WooCommerce 购物车中的一些东西,使用 PHP if 语句触发的 Javascript,这取决于购物车中的小计。我已成功使用以下代码获取小计:

global $woocommerce;
$subt = $woocommerce->cart->subtotal;

不幸的是,购物车也可以用 Ajax 更新,而无需重新加载页面,这意味着我的计算被抛出了。

我认为我需要使用 Ajax 更新购物车总数,但我在网上查看的解决方案似乎更适合更复杂的解决方案,我找不到将其归结为仅检索小计值的方法。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript php wordpress woocommerce


    【解决方案1】:

    一种解决方案是使用 Javascript 在购物车中添加查找更改,如果有任何更改,则使用 Ajax 调用 PHP 函数。你可以在这里阅读如何做:https://codex.wordpress.org/AJAX_in_Plugins

    假设这是你的 PHP 函数:

    add_action( 'wp_ajax_my_action', 'my_action' );
    
    function my_action() {
        global $wpdb;
    
        $whatever = intval( $_POST['whatever'] );
    
        $whatever += 10;
    
        echo $whatever;
    
        wp_die();
    }
    

    那么这就是你的 JS 脚本:

    jQuery( document.body ).on( 'updated_cart_totals', function(){
         var data = {
            'action': 'my_action',
            'whatever': ajax_object.we_value
        };
        jQuery.post(ajax_object.ajax_url, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2016-10-06
      • 1970-01-01
      相关资源
      最近更新 更多