我是WooCommerce的新手,想要检查用户是否在过去60天内购买了特定产品(产品编号为#514)。这是我让人们每月购买的产品,所以它会重现很多。我想看看他们是否购买了最近的(我认为是活跃的)
我现在想的方法是:
虽然我确信这会有效但我有一种有趣的感觉,有一个非常简洁的 get_posts(apply_filters(查询)可以节省一些循环时间。
有人愿意分享一些想法或解决方案吗?
谢谢!
答案 0 :(得分:2)
这是一个条件函数,部分基于内置的woocommerce函数wc_customer_bought_product
源代码查询:
有3个可选参数$user_id
,$product_ids
和$days
:
$user_id
将允许您指定已定义的用户ID(当未用于当前登录用户时); $product_ids
(字符串或数组)将允许指定要检查的已定义产品ID $days
将允许您指定搜索的天数(或者您喜欢的时间段) ... 代码功能:
function has_bought_multi( $user_id = 0, $product_ids = 0, $days = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 || $user_id == '' ? get_current_user_id() : $user_id;
$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
$date = date('Y-m-d H:i:s', strtotime("-$days day") );
if ( is_array( $product_ids ) )
$product_ids = implode(',', $product_ids);
if ( $product_ids != ( 0 || '' ) )
$query_line = "AND woim.meta_value IN ($product_ids)";
else
$query_line = "AND woim.meta_value != 0";
// Count the number of products
$product_count_query = $wpdb->get_col( "
SELECT COUNT(woim.meta_value) FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
AND p.post_date > '$date'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
AND woim.meta_key IN ( '_product_id', '_variation_id' )
$query_line
" );
// Set the count in a string
$count = reset($product_count_query);
// Return a boolean value if count is higher than 0
return $count > 0 ? true : false;
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
此代码在Woocommerce 3+上进行测试并正常运行。
类似的答案:Check if a customer has purchased a specific products in WooCommerce
用法示例(客户已登录):
检测当前用户是否在过去60天内购买了您的产品ID#514:
if( has_bought_multi( '', 514, 60 ) ){
echo "<p>Customer has bought product id # 514 in past 60 days</p>";
// do something
} else {
echo "<p>Customer <strong>HAS NOT</strong> bought product id # 514 in past 60 days</p>";
// do something else
}