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

为WooCommerce后台优惠券列表添加‘使用限制>产品’列

在WooCommerce后台优惠券列表添加“使用限制>产品”列

要实现这个需求,你可以通过WooCommerce提供的两个核心钩子完成:一个负责添加新列,另一个负责填充列内容。直接将以下代码添加到主题functions.php文件或自定义插件中即可:

1. 注册新列

先在优惠券列表的表头添加“使用限制>产品”列:

add_filter( 'manage_edit-shop_coupon_columns', 'add_coupon_product_restriction_column' );
function add_coupon_product_restriction_column( $columns ) {
    // 在现有列中插入新列(这里放在最后,可根据需求调整位置)
    $columns['product_restrictions'] = '使用限制>产品';
    return $columns;
}

2. 填充列的产品内容

接着获取每个优惠券关联的限制产品,并在列中展示:

add_action( 'manage_shop_coupon_posts_custom_column', 'display_coupon_product_restrictions', 10, 2 );
function display_coupon_product_restrictions( $column, $post_id ) {
    if ( $column === 'product_restrictions' ) {
        // 获取优惠券的产品限制元数据
        $restricted_products = get_post_meta( $post_id, 'product_ids', true );
        
        if ( empty( $restricted_products ) ) {
            echo '<em>无产品限制</em>';
            return;
        }
        
        // 处理存储格式:将字符串转为数组
        if ( is_string( $restricted_products ) ) {
            $restricted_products = array_filter( explode( ',', $restricted_products ) );
        }
        
        // 生成产品链接列表
        $product_items = [];
        foreach ( $restricted_products as $product_id ) {
            $product = wc_get_product( $product_id );
            if ( $product ) {
                $edit_url = get_edit_post_link( $product_id );
                $product_items[] = "<a href='{$edit_url}' target='_blank'>{$product->get_name()}</a>";
            }
        }
        
        echo implode( ', ', $product_items );
    }
}

代码说明:

  • manage_edit-shop_coupon_columns钩子用于修改优惠券列表的表头,我们在这里注册了自定义列的标题。
  • manage_shop_coupon_posts_custom_column钩子负责输出每行的内容:
    • 通过get_post_meta读取WooCommerce存储优惠券产品限制的product_ids字段。
    • 无限制时显示提示文本,有产品时将ID转为数组,循环生成带编辑链接的产品名称,方便后台直接跳转编辑。
    • 最终用逗号分隔展示所有关联产品。

添加代码后刷新优惠券列表页面,就能看到新的“使用限制>产品”列,里面会显示对应优惠券关联的所有限制产品。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:58:19