我遇到了一个问题。我需要使用用户ID和产品ID获取特定的产品购买日期。使用“ Checking if customer has already bought something in WooCommerce” 答案代码,它将检查以下所有产品:
def isEditDistanceOne(s1, s2):
isoneEdit = False
short = s1 if len(s1) < len(s2) else s2
longg = s2 if len(s1) < len(s2) else s1
if len(longg) - len(short) > 1:
return False
ind1 = 0
ind2 = 0
while ind1 < len(short) and ind2 < len(longg):
if short[ind1] != longg[ind2]:
if isoneEdit:
return False
isoneEdit = True
if len(short) == len(longg):
ind1 += 1
else:
ind1 += 1
ind2 += 1
return True
我需要使用用户ID和产品ID检查特定的产品购买数据。
我该如何实现?
答案 0 :(得分:1)
使用直接自定义SQL查询,避免在订单项中循环查找目标产品,这将使数据库查询和php处理更加轻松和有效。
查询还会检查所有产品类型,包括产品和产品变体。
现在在这里输入日期,我们使用订单发布日期。
这是嵌入在函数中的自定义查询(返回日期或空值):
function get_product_purchased_last_date( $product_id, $user_id ) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( "
SELECT p.post_date FROM {$wpdb->prefix}posts p
INNER JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items oi ON oi.order_id = p.ID
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim ON oi.order_item_id = oim.order_item_id
WHERE p.post_type = 'shop_order' AND p.post_status = 'wc-completed'
AND pm.meta_key = '_customer_user' AND pm.meta_value = '%d'
AND oim.meta_key IN ('_product_id','_variation_id') AND oim.meta_value = '%d'
ORDER BY p.ID DESC LIMIT 1
", $user_id, $product_id ) );
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
用法示例(在当前产品页面上,用于当前用户ID):
if( is_user_logged_in() ) {
if( $date = get_product_purchased_last_date( get_the_id(), get_current_user_id() ) ) {
$text = sprintf( __("You have already purchased this product the %s"), date( "jS \of F Y", strtotime($date) ) );
} else {
$text = __("Welcome, for your first purchase you will get a discount of 10%");
}
// Display
echo '<p>' . $text . '</p>';
}
答案 1 :(得分:0)
根据您的评论,您将需要遍历订单并检查产品ID是否存在。如果是,它将返回日期,否则将返回false。
function check_date_purchased($user_id, $product_id){
$args = array(
"posts_per_page" => -1,
"customer_id" => $user_id,
"orderby" => 'date',
"order" => 'DESC',
"status" => "completed", // maybe limit this to completed and processing,
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
foreach( $orders as $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ($items as $order_item){
if ($product_id == $order_item->get_product_id()) return $order->order_date;
}
}
return false;
}
(未测试)