首页 >后端开发 >php教程 >如何确定 WooCommerce 客户是否有购买历史记录?

如何确定 WooCommerce 客户是否有购买历史记录?

Patricia Arquette
Patricia Arquette原创
2024-11-13 13:09:02981浏览

How to Determine if a WooCommerce Customer Has a Purchase History?

确定客户在 WooCommerce 中的购买历史

开发 WooCommerce 插件时,通常有必要检查客户之前是否进行过购买。这些信息可用于相应地定制优惠和促销活动。

检查客户购买历史记录

要确定客户是否进行过任何购买,轻量级且优化的函数可以受雇:

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;
}

用法示例

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.根据账单电子邮件检查来宾用户购买情况:

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

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

通过使用此功能,插件开发人员可以轻松确定客户在 WooCommerce 中是否有购买历史记录,从而为增强的客户提供有针对性的促销和折扣订婚。

以上是如何确定 WooCommerce 客户是否有购买历史记录?的详细内容。更多信息请关注PHP中文网其他相关文章!

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