我有以下循环用于在客户仪表板的我的帐户部分中的页面上获取 Woocommerce 优惠券。
目前我们有 10k 多张优惠券,仅通过执行这个循环,就会大量消耗资源,而且效率不高,会导致超时。有什么明显的方法可以提高它的效率吗?
有什么方法可以将循环限制为仅在“允许的电子邮件”字段中搜索电子邮件(因为每个优惠券都与一个电子邮件地址相关联)?
<?php $smart_coupons = get_posts( array(
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'desc',
'post_type' => 'shop_coupon',
'post_status' => 'publish'
) );
if ( $smart_coupons ) {
foreach( $smart_coupons as $smart_coupon) {
$strcode = strtolower($smart_coupon->post_title);
$full_coupon = new WC_Coupon( $strcode ); ?>
<?php if($full_coupon->discount_type == "smart_coupon"){
$emails = $full_coupon->get_email_restrictions();
if (in_array($current_email, $emails)) {
if($full_coupon->usage_count < $full_coupon->usage_limit){ ?>
coupon content
<?php }
}
}
}
}
答案 0 :(得分:3)
由于电子邮件限制在一个数组中(因此是数据库中的索引数组),由于许多技术原因,不可能从 WP_Query 中的元查询中获取它。
现在,您可以使用 WPDB
类执行自定义的非常轻量且有效的 SQL 查询,以获取属于电子邮件的“智能”优惠券。
我在下面的函数中嵌入了这个 SQL 查询(其中 $discount_type
参数已经设置为“smart_coupon”):
function get_coupons_from_email( $current_email, $discount_type = 'smart_coupon' ) {
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
INNER JOIN {$wpdb->prefix}postmeta pm2
ON p.ID = pm2.post_id
WHERE p.post_type = 'shop_coupon'
AND p.post_status = 'publish'
AND pm.meta_key = 'discount_type'
AND pm.meta_value = '%s'
AND pm2.meta_key = 'customer_email'
AND pm2.meta_value LIKE '%s'
ORDER BY p.post_name DESC
", $discount_type, '%'.$current_email.'%' ) );
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。
现在您可以在代码中使用它,如下所示:
// Get smart coupons from email
$smart_coupon_codes = get_coupons_from_email( $current_email );
if ( count($smart_coupon_codes) > 0 ) {
// Loop through smart coupons code
foreach ( $smart_coupon_codes as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code ); // Get the WC_Coupon Object
if( $coupon->get_usage_count() < $coupon->get_usage_limit() ){
?>
<p>coupon content</p>
<?php
}
}
}
现在应该可以顺利运行了。