1

I would like to output for the current logged in user, how many times they have used a specific coupon code.

The coupon code "example_coupon" has a maximum "Usage limit per user" of 12. I would like to display on the front end to the user how many times they have used that coupon, E.G. "Number of coupon uses: 3"

I have this code below running, however, it only shows me the total amount of coupon usage from all users:

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' );

Hope all this makes sense.

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
James_Www
  • 13
  • 2

1 Answers1

0

The following shortcode will display

  • How many times a specific coupon has been used
  • The usage limit per user
  • Based on the user id of the currently logged in user.
// 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' );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50