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

WordPress自定义分类模板taxonomy-product_brand.php动态数据获取求助

WooCommerce product_brand 自定义分类页动态数据获取方案

你已经创建的taxonomy-product_brand.php文件完全符合WordPress自定义分类模板的命名规则,可直接通过以下代码获取当前页面的全部品牌相关数据:


1. 获取当前品牌核心基础数据

在模板文件顶部插入以下代码即可拿到当前访问品牌的全局对象,可直接提取需要的字段使用:

// 获取当前访问品牌的分类对象
$current_brand = get_queried_object();

// 常用基础字段直接提取调用
$brand_id = $current_brand->term_id; // 品牌唯一ID
$brand_name = $current_brand->name; // 品牌显示名称
$brand_slug = $current_brand->slug; // 品牌URL别名
$brand_desc = $current_brand->description; // 后台填写的品牌描述
$brand_product_count = $current_brand->count; // 该品牌下已发布产品总数

2. 获取品牌自定义字段数据

Kapee主题内置的品牌分类额外字段(如品牌Logo、官网链接等)都存在WordPress term_meta表中,使用get_term_meta函数即可读取:

// 获取品牌Logo(Kapee主题默认字段名为brand_logo,若不匹配可按下方注调整)
$brand_logo_id = get_term_meta($brand_id, 'brand_logo', true);
// 输出品牌Logo示例
if ($brand_logo_id) {
    echo wp_get_attachment_image($brand_logo_id, 'medium', false, ['alt' => $brand_name]);
}

// 获取品牌官网链接(默认字段名brand_website)
$brand_website = get_term_meta($brand_id, 'brand_website', true);

// 其他自定义字段均可通过更换第二个参数的字段名获取
$custom_field_val = get_term_meta($brand_id, '你的自定义字段名', true);

注:如果上述字段名和你当前使用的Kapee主题版本不匹配,可在后台品牌分类编辑页右键点击对应输入框,查看元素的name属性值即为实际字段名


3. 获取当前品牌下的产品列表

如果需要在页面输出该品牌对应的产品,可通过WP_Query自定义查询实现,且兼容WooCommerce原生产品样式:

// 品牌产品查询参数
$product_query_args = [
    'post_type' => 'product',
    'posts_per_page' => 12, // 可自定义每页显示产品数
    'post_status' => 'publish',
    'tax_query' => [
        [
            'taxonomy' => 'product_brand',
            'field' => 'term_id',
            'terms' => $brand_id
        ]
    ],
    'orderby' => 'date', // 可改为price、sales等排序规则
    'order' => 'DESC'
];
$brand_product_query = new WP_Query($product_query_args);

// 输出产品列表示例
if ($brand_product_query->have_posts()) {
    // 调用WooCommerce/主题原生的产品列表容器,保证样式统一
    woocommerce_product_loop_start();
    
    while ($brand_product_query->have_posts()) {
        $brand_product_query->the_post();
        // 调用主题自带的产品卡片模板
        wc_get_template_part('content', 'product');
    }
    
    woocommerce_product_loop_end();

    // 输出分页
    echo paginate_links([
        'total' => $brand_product_query->max_num_pages
    ]);

    // 重置主查询,避免影响页面其他内容
    wp_reset_postdata();
} else {
    echo '<p class="no-product-tip">该品牌下暂无上架产品</p>';
}

URL格式补充说明

如果当前品牌页URL不符合Website_Address/brand/brand_name格式,可直接进入WordPress后台→设置→固定链接,找到自定义分类法的固定链接设置项,将product_brand的前缀设置为brand,保存后刷新即可生效,无需修改代码。


内容的提问来源于stack exchange,提问作者Asfand Yar Ali Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:57:00