代码之家  ›  专栏  ›  技术社区  ›  James Donald

显示购物车和收银台购物篮中的商品总数,以及收到的电子邮件订单

  •  1
  • James Donald  · 技术社区  · 7 年前

    我试图在不同位置显示购物车中的物品总数

    1) 购物车页面 2) 签出页面 3) 通过电子邮件向客户发送订单收据 4) 通过电子邮件将订单收据发送给管理员

    我正在使用以下函数计算购物车中的项目总数

     // function to calc total number items in basket
     function gh_custom_checkout_field( $checkout ) {        
     return WC()->cart->get_cart_contents_count();
     } 
    

    有人知道我如何在上面的位置显示值吗?

    我已尝试使用my\u custom\u checkout\u field()&燃气轮机;但这只是给出了一个内部服务器错误。

    1 回复  |  直到 7 年前
        1
  •  1
  •   LoicTheAztec    7 年前

    (1) 用于购物车和结帐

    您可以使用您的功能 (无 $checkout 变量,因为不需要) 作为短代码:

    function get_cart_count() {        
        return WC()->cart->get_cart_contents_count();
    }
    add_shortcode( 'cart_count', 'get_cart_count');
    

    代码进入功能。活动子主题(或活动主题)的php文件。

    您将使用它:

    • 在WordPress文本编辑器中: [cart_count]
    • 在php代码中: echo do_shortcode( "[cart_count] ");
    • 在混合php/html代码中: <?php echo do_shortcode( "[cart_count] "); ?>

    (2) 订单和电子邮件通知

    因为对应的购物车对象不再存在 ,您需要从 WC_Order 对象(或订单ID,如果您没有)。

    您可以将此自定义函数与一个强制定义的参数一起使用,该参数可以是 WC\U订单 对象或订单ID。否则,函数将不返回任何内容:

    function get_order_items_count( $mixed ) {        
        if( is_object( $mixed ) ){
            // It's the WC_Order object
            $order = $order_mixed;
        } elseif ( ! is_object( $mixed ) && is_numeric( $mixed ) ) {
            // It's the order ID
            $order = wc_get_order( $mixed ); // We get an instance of the WC_order object
        } else {
            // It's not defined as an order ID or an order object: we exit
            return;
        }
        $count = 0
        foreach( $order->get_items() as $item ){
            // Count items
            $count += (int) $item->get_quantity()
        }
        return $count;
    }
    

    您将始终将其设置为现有动态变量函数的参数 $order_id $order 喜欢

    echo get_order_items_count( $order_id ); // Dynamic Order ID variable
    

    echo get_order_items_count( $order ); // Dynamic Order object variable