WooCommerce的购物车数据存储在两个地方,一个是woocommerce_sessions
数据表,另一个是在usermeta中,meta key是woocommerce_persistent_cart_[blog ID]
,blog ID指multisite的site ID。本文介绍查看所有用户购物车的方法,当然,是用程序读取。
目录
查看所有用户购物车的代码
- 从
wp_woocommerce_sessions
表中读取所有数据,代码只读取了10个,数据量很大时分页是必须的 session_key
是user ID的就是注册用户,session_key
是一个长长的字符串的代表游客session_value
里存储了所有购物车相关的数据,例如购物车里有什么产品,购物车的各种总价,税费,邮费等等。如果想知道具体有什么,可以var_dump
一下$cart_session
变量。$cart_session['cart']
里存储了购物车产品,这里简单用程序把产品信息打印出来(sola_list_cart_item
函数的作用)
/**
* Get all carts data from wp_woocommerce_sessions table
*
*/
function sola_get_all_carts_from_session() {
global $wpdb;
$carts = $wpdb->get_results("SELECT session_key,session_value FROM {$wpdb->prefix}woocommerce_sessions Limit 0,10");
foreach ($carts as $cart) {
$customer_id = $cart->session_key;
$cart_session = maybe_unserialize($cart->session_value);
$cart_totals = maybe_unserialize($cart_session['cart_totals']);
$cart_total = $cart_totals['total'];
echo '<p>';
if (is_numeric($customer_id)) {
$user = new WP_User($customer_id);
echo '注册用户: ' . $user->get('user_email');
} else {
echo '游客';
}
echo ', 购物车总价:', wc_price($cart_total), '<br>';
// List products in cart
sola_list_cart_item(maybe_unserialize($cart_session['cart']));
echo '</p>';
}
}
/**
* List products of cart
*/
function sola_list_cart_item($cart_items) {
// Loop through cart items and get cart items details
foreach ($cart_items as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
$quantity = $cart_item['quantity'];
$attributes = $cart_item['variation'];
$item_taxes = $cart_item['line_tax_data'];
$subtotal_tax = $cart_item['line_subtotal_tax'];
$total_tax = $cart_item['line_tax'];
$subtotal = $cart_item['line_subtotal'];
$total = $cart_item['line_total'];
$product = wc_get_product($product_id);
echo '<a href="', $product->get_permalink(), '">', $product->get_title(), '</a>, 数量:', $quantity, ', 单价', $product->get_price_html(), '<br>';
}
}
把代码做成shortcode运行一下的效果如下图所示:
根据用户ID列出购物车产品
function sola_get_cart_contents_by_user_id($user_id) {
// Get an instance of the WC_Session_Handler Object
$session_handler = new WC_Session_Handler();
// Get the user session from its user ID:
$session = $session_handler->get_session($user_id);
// Get cart items array
$cart_items = maybe_unserialize($session['cart']);
sola_list_cart_item($cart_items);
}
能实现此功能的插件
这些插件主要用来实现abandoned cart营销,功能更为强大,Retainful是第三方服务,所有查看功能要去它的网站才行。