我正在循环浏览仅限于登录客户的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
)
)
);上面的代码只返回与客户的电子邮件一起保存的优惠券,不返回同一封电子邮件在数组中的优惠券。如果有人想知道为什么电子邮件保存在customer_email元中,有时保存为唯一的,有时保存为数组,因为如果优惠券仅作为一封允许的电子邮件生成,则值是唯一的,如果它是用更多的电子邮件创建的,则它被保存为数组。知道为什么我的查询不返回包含客户电子邮件的所有优惠券吗?
发布于 2021-12-12 11:22:58
你能试试这个吗?
// 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
)
)
);编辑添加解释为什么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'
]编辑*其他方法
您应该看看这个线程:How to get coupons from email restrictions with efficiency in WooCommerce
受上述线索启发:
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.'%' )
);
}此函数返回限制在“$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();
}https://stackoverflow.com/questions/70319585
复制相似问题