如何获取并输出WooCommerce自定义分类下指定分类的所有文章标题?
获取WooCommerce指定分类下的产品标题
核心思路
WooCommerce的产品属于自定义文章类型product,对应的分类法默认是product_cat(你提到的“自定义分类法‘Category’”大概率指的就是这个),通过WP_Query结合分类查询就能拿到目标分类下的所有产品,再输出标题即可。
代码实现
// 配置参数:分类名称和对应分类法slug $target_category = 'Cable'; $taxonomy_slug = 'product_cat'; // 若为自定义分类法,替换成实际slug // 获取分类ID $category = get_term_by('name', $target_category, $taxonomy_slug); if ($category && !is_wp_error($category)) { // 查询分类下的所有产品 $product_query = new WP_Query([ 'post_type' => 'product', 'posts_per_page' => -1, // 不限制数量,获取全部 'tax_query' => [ [ 'taxonomy' => $taxonomy_slug, 'field' => 'term_id', 'terms' => $category->term_id ] ] ]); // 输出产品标题列表 if ($product_query->have_posts()) { echo '<ul>'; while ($product_query->have_posts()) { $product_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; wp_reset_postdata(); // 重置查询状态 } else { echo '该分类下暂无产品'; } } else { echo '未找到指定分类'; }
注意事项
- 如果你确实是自己注册的自定义分类法,一定要把
$taxonomy_slug改成你注册时用的slug(可以在后台分类编辑页的URL里找到,比如taxonomy=xxx中的xxx)。 - 代码可以直接放到主题模板文件(如
archive-product.php、single-product.php)里,或者做成短代码方便在页面/文章中调用:
// 注册短代码 function cable_products_titles_shortcode() { ob_start(); // 把上面的核心代码复制到这里 $content = ob_get_clean(); return $content; } add_shortcode('cable_product_titles', 'cable_products_titles_shortcode');
之后在页面中插入[cable_product_titles]就能显示标题列表了。
内容的提问来源于stack exchange,提问作者matt.mcg
相关产品推荐
相关产品推荐

