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

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


优惠券代码“ 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' );

希望这一切都有道理。


守着星空守着你
浏览 112回答 1
1回答

一只斗牛犬

将显示以下简码特定优惠券已使用多少次每个用户的使用限制基于当前登录用户的用户 ID。// Function that runs when shortcode is calledfunction users_coupon_usage_shortcode() {&nbsp; &nbsp; // Only for logged-in users&nbsp; &nbsp; if ( ! is_user_logged_in() ) return;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; global $wpdb;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Coupon code&nbsp; &nbsp; $coupon_code = 'test';&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Retrieving the coupon ID&nbsp; &nbsp; $coupon_post_obj = get_page_by_title( $coupon_code, OBJECT, 'shop_coupon' );&nbsp; &nbsp; $coupon_id&nbsp; &nbsp; &nbsp; &nbsp;= $coupon_post_obj->ID;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Get the WC_Coupon Object&nbsp; &nbsp; $coupon_data = new WC_Coupon( $coupon_id );&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Get current user id&nbsp; &nbsp; $user_id = get_current_user_id();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Usage limit per user&nbsp; &nbsp; $usage_limit_per_user = $coupon_data->get_usage_limit_per_user();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Get an array of used by count based on post_id, meta_key and meta_value (user_id)&nbsp; &nbsp; $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'");&nbsp; &nbsp; // Output&nbsp; &nbsp;&nbsp; &nbsp; $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 );&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; // Output needs to be return&nbsp; &nbsp; return $output;}&nbsp;// Register shortcodeadd_shortcode( 'users_coupon_usage', 'users_coupon_usage_shortcode' );
打开App,查看更多内容
随时随地看视频慕课网APP