【问题标题】:How to get coupons from email restrictions with efficiency in WooCommerce如何在 WooCommerce 中高效地从电子邮件限制中获取优惠券
【发布时间】:2023-05-22 20:39:01
【问题描述】:

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

【问题讨论】:

    标签: php sql wordpress woocommerce coupon


    【解决方案1】:

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

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

    【讨论】:

    • 一如既往的精彩!
    • @Rob 我之前尝试过使用元查询,但无法使用 LIKE %% 作为电子邮件的“比较”参数。
    • 是的,我发现了,它对我也不起作用,很高兴你能想出一个替代方案
    最近更新 更多