循环使用 WooCommerce 用户优惠券不起作用

Loop with WooCommerce user coupon not working

我正在循环浏览仅限登录客户使用的 WooCommerce 优惠券。问题是保存有客户限制的优惠券有 post_meta "customer_email" 有时是单个值,有时是数组。使用 WP_QUERY 进行查询时,我无法获得数组格式的目标“customer_email”的优惠券。我的代码示例:

              // LOOP ACROSS ALL COUNPONS IN WOOCOMMERCE
              $args = array(
                    'post_type' => 'shop_coupon',
                    'meta_query'  => array(
                             'relation' => 'OR',
                             array(
                                 'key'   => 'customer_email',
                                 'value' => array($user_email),
                                 'compare' => 'IN'
                             ),
                             array(
                                 'key'   => 'customer_email',
                                 'value' => $user_email
                             )
                         )

                );

上面的代码只returns 与客户的电子邮件唯一保存的优惠券,同一电子邮件在数组中的优惠券没有returned。 如果有人想知道为什么电子邮件保存在 customer_email 元中,有时是唯一的,有时是一个数组,这是因为如果优惠券生成为只允许一封电子邮件,则该值是唯一的,如果它是用创建的更多的电子邮件被保存为一个数组。知道为什么我的查询没有 return 所有包含客户电子邮件的优惠券吗?

你能试试这个吗:

// LOOP ACROSS ALL COUNPONS IN WOOCOMMERCE
$args = array(
    'post_type' => 'shop_coupon',
    'meta_query'  => array(
        array(
            'key'   => 'customer_email',
            'value' => $user_email,
            'compare' => 'LIKE' // search will match in both cases : single value and array value
        )
    )
);

EDIT 添加说明为什么 IN 在这种情况下不匹配 'customer_email' 是一个包含所有用逗号分隔的电子邮件的字符串。

customer_email.value = email1,email2,email3

当我们使用 IN 时,我们正在寻找 DB 值和我们在数组中传递的每个值的精确对应值。

[
    // ...
    "IN" => [ 'email1', 'email2' ]
    // Corresponding search :  customer_email.value = 'email1' OR customer_email.value = 'email2'
    // This can't match because customer_email.value = 'email1,email2,email3'

]

编辑 *** 其他方式

你应该看看这个线程:

灵感来自于以上话题:

function get_coupons_names_from_email( $current_email ) {
    global $wpdb;

    return $wpdb->get_col( $wpdb->prepare("
        SELECT p.post_name
        FROM {$wpdb->prefix}posts p
        INNER JOIN {$wpdb->prefix}postmeta pm
            ON p.ID = pm.post_id
        WHERE p.post_type = 'shop_coupon'
            AND p.post_status = 'publish'
            AND pm.meta_key = 'customer_email'
            AND pm.meta_value LIKE '%s'
        ORDER BY p.post_name DESC", 
        '%'.$current_email.'%' ) 
    );
}

此功能return所有优惠券代码仅限于“$current_email”(客户电子邮件)。

在您的脚本中,如果您需要 WC_Coupon 对象,您可以像这样检索它:

$user = wp_get_current_user();
$coupons_codes = get_coupons_names_from_email( $user->user_email );
foreach ( $coupons_codes as $coupon_code ) {
    $coupon = new WC_Coupon( $coupon_code ); // Return the WC_Coupon object refreshed with data related to $coupon_code
    // do your stuff
    // $coupon->get_code();
    // $coupon->get_description();
}