You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce优惠券列表短代码中获取更多信息?

解决方案

你可以通过WooCommerce内置的WC_Coupon类来获取优惠券的详细信息,替代直接操作post对象的方式,这样能更安全可靠地获取到期日、优惠金额等字段。以下是修改后的短代码:

add_shortcode('ac', 'coupon_list');
function coupon_list() {
    // 获取所有已发布的优惠券
    $coupon_posts = get_posts(array(
        'posts_per_page' => -1,
        'orderby'        => 'name',
        'order'          => 'asc',
        'post_type'      => 'shop_coupon',
        'post_status'    => 'publish',
    ));

    if (empty($coupon_posts)) {
        return '暂无可用优惠券';
    }

    // 构建优惠券列表的HTML
    $output = '<ul class="coupon-list">';

    foreach ($coupon_posts as $coupon_post) {
        // 初始化WC_Coupon对象
        $coupon = new WC_Coupon($coupon_post->ID);

        // 获取优惠券信息
        $code = $coupon->get_code();
        $description = !empty($coupon_post->post_content) ? $coupon_post->post_content : '无描述';
        $expiry_date = $coupon->get_date_expires();
        $formatted_expiry = $expiry_date ? date('Y-m-d', strtotime($expiry_date)) : '无到期日';
        $amount = $coupon->get_amount();
        $discount_type = $coupon->get_discount_type();
        
        // 格式化优惠金额显示(区分固定金额和百分比)
        $display_amount = $discount_type === 'percent' ? $amount . '%' : wc_price($amount);

        // 添加到输出
        $output .= sprintf(
            '<li class="coupon-item">
                <strong>优惠券代码:</strong>%s<br>
                <strong>优惠内容:</strong>%s<br>
                <strong>到期日期:</strong>%s<br>
                <strong>优惠金额:</strong>%s
            </li>',
            esc_html($code),
            esc_html($description),
            esc_html($formatted_expiry),
            wp_kses_post($display_amount)
        );
    }

    $output .= '</ul>';

    return $output;
}

关键说明:

  • 使用WC_Coupon类:WooCommerce的优惠券逻辑都封装在这个类里,直接调用方法比手动读取post_meta更稳定,避免元键变更导致的问题。
  • 字段获取:
    • 优惠券代码:get_code() 比直接用post_name更准确,因为优惠券代码可以和post名称不同
    • 描述:直接取post的post_content,对应后台编辑优惠券时填写的描述内容
    • 到期日:get_date_expires() 返回日期对象,用date()格式化后更易读
    • 优惠金额:get_amount() 获取数值,结合get_discount_type()区分百分比和固定金额,用wc_price()格式化货币显示
  • 安全处理:用esc_html()和wp_kses_post()处理输出内容,避免XSS风险
  • 空状态处理:如果没有优惠券,返回友好提示

你可以根据需求调整HTML结构(比如改成表格)或者添加更多样式类来美化显示。

内容的提问来源于stack exchange,提问作者Lgane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:03:23