如何从自定义分类术语数组中输出指定的product_type术语(带链接)
嘿,我来帮你搞定这个问题!在WordPress单产品页面输出指定的自定义分类术语(带链接)其实很简单,核心思路是先获取当前产品关联的所有product_type术语,再筛选出你需要的那些,最后生成带链接的输出。
这里给你一个完整的可直接使用的代码示例,你可以把它放到你的单产品模板(比如single-products.php)或者主题的functions.php里:
<?php // 获取当前产品的所有product_type术语 $product_terms = get_the_terms(get_the_ID(), 'product_type'); // 指定你要显示的术语SLUG(推荐用slug,比名称更稳定) $target_terms = ['new-arrivals', 'featured', 'tv']; // 对应你例子里的New arrivals、featured、tv // 检查是否获取到术语且无错误 if (!empty($product_terms) && !is_wp_error($product_terms)) { // 遍历所有术语 foreach ($product_terms as $term) { // 如果当前术语的slug在目标列表里,就输出带链接的术语 if (in_array($term->slug, $target_terms)) { $term_link = get_term_link($term); // 确保链接有效 if (!is_wp_error($term_link)) { echo '<a href="' . esc_url($term_link) . '" rel="tag">' . esc_html($term->name) . '</a> '; } } } } ?>
代码细节说明:
get_the_terms(get_the_ID(), 'product_type'):获取当前产品文章关联的所有product_type分类术语,返回一个术语对象数组。$target_terms:这里放你想要显示的术语的slug,slug是术语的小写连字符形式(比如“New arrivals”的slug通常是new-arrivals,你可以在WP后台的分类管理里查看每个术语的slug)。- 循环遍历术语数组,用
in_array检查当前术语是否在目标列表中,符合条件的就用get_term_link()获取术语的归档页面链接,然后输出带链接的术语名称。 - 用
esc_url()和esc_html()做安全转义,避免XSS漏洞,这是WordPress开发的最佳实践。
如果你更习惯用术语名称来匹配(不推荐,因为名称可能被修改),可以把判断条件改成:
if (in_array($term->name, $target_terms))
对应的$target_terms就写成['New arrivals', 'featured', 'tv']。
这样修改后,就能在单产品页面精准输出你指定的那些带链接的自定义分类术语啦!
内容的提问来源于stack exchange,提问作者Charlesbz
相关产品推荐
相关产品推荐

