如何在WooCommerce中查看优惠券的时间?

时间:2018-06-04 09:29:37

标签: php wordpress woocommerce

我正在编写自定义插件,我需要自动发送有关每个新创建的优惠券的信息。到目前为止,我只能按名称选择特定的优惠券(例如1234):
 $coupon = new WC_Coupon("1234");

但我似乎无法找到如何在创建优惠券之后立即获得优惠券,而不知道其名称,或者至少如何获得所有优惠券。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

可能这可能会有所帮助。经过测试,它正在运行。这将返回所有优惠券,因为优惠券保存为post_type shop_coupon

$args = array(
    'posts_per_page'   => -1,
    'orderby'          => 'title',
    'order'            => 'asc',
    'post_type'        => 'shop_coupon',
    'post_status'      => 'publish',
);

$coupons = get_posts( $args );

答案 1 :(得分:0)

尝试使用自定义帖子类型或直接使用mysql查询。

1)使用mysql查询

            // Run a query on the postmeta table to get the id of every coupon that has the email in the customer_email restrictions
              $couponlist = $wpdb->get_results("SELECT 
                             `wp_postmeta`.`post_id`
                              FROM `wp_postmeta`
                             WHERE `wp_postmeta`.`meta_key` LIKE 'customer_email'
                              AND `wp_postmeta`.`meta_value` LIKE '%".$email."%'");
           $couponarrayfinal = array( );  //Create an array of the ids so we can use wp_query to more quickly grab the data

          // Add the ids to the array in a foreach loop
             foreach( $couponlist as $key => $row) {

                 $value = $row->post_id;
                 $couponarrayfinal[] = $value ;
                 }

2)使用get_posts方法

       $arg = array(
'posts_per_page'   => -1,
'orderby'          => 'title',
'order'            => 'asc',
'post_type'        => 'shop_coupon',
'post_status'      => 'publish');

     $coupons_list = get_posts( $arg );

答案 2 :(得分:0)

尝试使用此功能,您将获得所有数据

// WP_Query arguments
$args = array(
    'post_type' => array('shop_coupon'),
    'post_status' => array('publish'),
    'posts_per_page' => '-1',
    'order' => 'DESC',
    'orderby' => 'id',
);

// The Query
$query = new WP_Query($args);

// The Loop
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // do something

        $coupon = new WC_Coupon(get_the_ID());
        $coupnCode = $coupon->code;
        $coupnAmount = $coupon->amount;
        $minAmount = wc_format_decimal($coupon->minimum_amount, 2);
        $maximumAmount = wc_format_decimal($coupon->maximum_amount, 2);
        $expire = $coupon->expiry_date;

    }
} else {
    // no posts found
}

// Restore original Post Data
wp_reset_postdata();