在购物车和结账时显示购物篮中的商品总数,并通过电子邮件发送订单收据

Display total number of items in basket on cart and checkout, and email order reciept

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

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_custom_checkout_field() ?> 但这只会导致内部服务器错误。

1) 用于购物车和结帐

您可以使用您的函数 (不需要 $checkout 变量) 作为短代码:

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

代码进入您的活动子主题(或活动主题)的 function.php 文件。

你会用到它:

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

2) 对于订单和电子邮件通知

As the corresponding cart object doesn't exist anymore, you need to get the order items count from the WC_Order object (or the Order ID if you dont have it).

您可以使用此自定义函数,其中必须定义一个参数,该参数可以是 WC_Order 对象或订单 ID。如果不是,该函数将 return 什么都没有:

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