gpt4 book ai didi

php - 检查客户是否已经在 WooCommerce 中购买了东西

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:38 25 4
gpt4 key购买 nike

我想创建一个 WooCommerce 插件来为客户(有购买历史)添加一些优惠。

如何查看用户之前购买过的东西?

谢谢。

最佳答案

2021 UPDATE - Handling guests "billing email" - Improved and secured SQL query

这是一个更轻量级和更快的条件函数,如果客户已经购买,它将返回 true。

它处理来自其用户 ID 的注册用户 guest 和来自其帐单电子邮件的 guest :

  • 对于注册用户:如果可选参数未设置用户 ID,则将使用当前用户 ID。
  • 对于客人:帐单电子邮件将需要作为函数中的参数。

这个更轻量和改进的函数(部分基于wc_customer_bought_product()函数源代码)将返回一个基于订单计数的 bool 值(O订单为false,至少有订单为true一个付费订单):

function has_bought( $value = 0 ) {
if ( ! is_user_logged_in() && $value === 0 ) {
return false;
}

global $wpdb;

// Based on user ID (registered users)
if ( is_numeric( $value) ) {
$meta_key = '_customer_user';
$meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value;
}
// Based on billing email (Guest users)
else {
$meta_key = '_billing_email';
$meta_value = sanitize_email( $value );
}

$paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );

$count = $wpdb->get_var( $wpdb->prepare("
SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' )
AND p.post_type LIKE 'shop_order'
AND pm.meta_key = '%s'
AND pm.meta_value = %s
LIMIT 1
", $meta_key, $meta_value ) );

// Return a boolean value based on orders count
return $count > 0;
}

代码位于您的事件子主题(或主题)的 functions.php 文件中或任何插件文件中。

此代码已在 Woocommerce 3+ 上测试并有效(它应该也适用于以前的版本)。

For multiple products: Check if a user has purchased specific products in WooCommerce


使用示例 1 (登录客户)

if( has_bought() )
echo '<p>You have already made a purchase</p>';
else
echo '<p>Welcome, for your first purchase you will get a discount of 10%</p>';

使用示例2 (设置用户ID)

// Define the user ID
$user_id = 85;

if( has_bought( $user_id ) )
echo '<p>customer have already made a purchase</p>';
else
echo '<p>Customer with 0 purchases</p>';

如果未定义$user_id 且当前用户未登录,则此函数将返回false

使用示例 3 - For guests (设置账单电子邮件)

// Define the billing email (string)
$email = 'louis.fourteen@gmail.com';

if( has_bought( $email ) )
echo '<p>customer have already made a purchase</p>';
else
echo '<p>Customer with 0 purchases</p>'

The code of this function is partially based on the built in WooCommerce function wc_customer_bought_product() source code.

关于php - 检查客户是否已经在 WooCommerce 中购买了东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38874189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com