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) 订单和电子邮件通知
由于相应的购物车对象不再存在,您需要从WC_Order 对象(如果没有,则为订单ID)获取订单商品数。
您可以使用此自定义函数,并带有一个强制定义的参数,该参数可以是 WC_Order 对象或订单 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