如何在 WooCommerce 中高效地从电子邮件限制中获取优惠券

问题描述

我有以下循环用于在客户仪表板的我的帐户部分中的页面上获取 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 }
        }
      }
  }
}

解决方法

由于电子邮件限制在一个数组中(因此是数据库中的索引数组),由于许多技术原因,不可能从 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
        }
    }
}

现在应该可以顺利运行了。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...