首页 >后端开发 >php教程 >如何检查 WooCommerce 用户过去是否进行过购买?

如何检查 WooCommerce 用户过去是否进行过购买?

Patricia Arquette
Patricia Arquette原创
2024-11-14 14:32:021024浏览

How to Check if a WooCommerce User Has Made Past Purchases?

检查 WooCommerce 中的购买历史记录

问题:

您希望创建 WooCommerce 插件为有购买历史的客户提供独家优惠。挑战在于确定用户过去是否进行过购买。

解决方案:

检查客户过去的购买

要检查客户过去是否进行过任何购买,您可以利用无缝处理注册用户和访客用户的自定义函数:

function has_bought( $value = 0 ) {
    // Handling for registered users
    if ( is_numeric( $value) ) { 
        // Use current user ID if not provided
        $meta_key   = '_customer_user';
        $meta_value = $value == 0 ? (int) get_current_user_id() : (int) $value;
    } 
    // Handling for guest users
    else { 
        $meta_key   = '_billing_email';
        $meta_value = sanitize_email( $value );
    }
    
    global $wpdb;
    
    // Determine if any paid orders exist
    $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 true if at least one paid order exists
    return $count > 0;
}

使用示例:

示例 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>';

示例 3: 通过访客用户的账单电子邮件检查购买情况

// Define the billing email (string)
$email = '[email protected]';

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

以上是如何检查 WooCommerce 用户过去是否进行过购买?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn