如何输出当前登录 WooCommerce 用户的优惠券使用情况?

How to output the current logged in WooCommerce users coupon usage?

我想为当前登录的用户输出他们使用特定优惠券代码的次数。

优惠券代码“example_coupon”的最大“每次使用限制r”为12。我想在前端向用户显示他们使用该优惠券的次数,例如"优惠券使用次数:3"

我下面有这段代码 运行,但是,它只显示了所有用户的优惠券使用总量:

function simple_function_1() {
    
    $coupon_code = 'example_coupon';
    global $woocommerce;
    $coupon_data = new WC_Coupon($coupon_code);
    echo ($coupon_data->usage_limit - $coupon_data->usage_count);// return number of remaining coupons
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );

希望这一切都有意义。

将显示以下简码

  • 特定优惠券已使用多少次
  • 每个用户的使用限制
  • 基于当前登录用户的用户id。
// Function that runs when shortcode is called
function users_coupon_usage_shortcode() {
    // Only for logged-in users
    if ( ! is_user_logged_in() ) return;
    
    global $wpdb;
    
    // Coupon code
    $coupon_code = 'test';
    
    // Retrieving the coupon ID
    $coupon_post_obj = get_page_by_title( $coupon_code, OBJECT, 'shop_coupon' );
    $coupon_id       = $coupon_post_obj->ID;
    
    // Get the WC_Coupon Object
    $coupon_data = new WC_Coupon( $coupon_id );
    
    // Get current user id
    $user_id = get_current_user_id();
    
    // Usage limit per user
    $usage_limit_per_user = $coupon_data->get_usage_limit_per_user();
    
    // Get an array of used by count based on post_id, meta_key and meta_value (user_id)
    $used_by_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id = '$coupon_id' AND meta_key = '_used_by' AND meta_value = '$user_id'");

    // Output   
    $output = sprintf( __( 'The coupon %s has already been used %s times out of %s', 'woocommerce' ), '"<strong>' . $coupon_code . '</strong>"', $used_by_count, $usage_limit_per_user );
     
    // Output needs to be return
    return $output;
} 
// Register shortcode
add_shortcode( 'users_coupon_usage', 'users_coupon_usage_shortcode' );