如何在WordPress短码中限制仅显示当前分类的文章?
解决方案
要让短码在分类归档页面仅展示当前分类的文章,核心是动态获取当前归档页的分类ID,无需硬编码。修改后的代码如下:
function archive_loop_shortcode() { // 初始化查询参数 $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 3, ); // 仅在分类归档页面时,添加当前分类限制 if (is_category()) { $current_category = get_queried_object(); if ($current_category instanceof WP_Term) { $args['category'] = $current_category->term_id; } } $my_query = new WP_Query($args); if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); // 输出文章内容结构 echo "<div>" . get_the_post_thumbnail() . "</div>"; echo "<h3>" . get_the_title() . "</h3>"; endwhile; wp_reset_postdata(); else : _e('Sorry, no posts matched your criteria.'); endif; } add_shortcode('archive_loop', 'archive_loop_shortcode');
关键修改说明
is_category():判断当前页面是否为分类归档页,避免在非分类页面(如首页、单页)添加分类限制。get_queried_object():获取当前页面的查询对象,在分类归档页会返回一个WP_Term对象,包含当前分类的所有信息。$args['category'] = $current_category->term_id:将当前分类ID添加到查询参数中,让WP_Query仅查询该分类下的文章。
额外说明
如果短码可能被用在自定义分类归档页(而非默认分类),可以将is_category()替换为is_tax(),并调整分类参数为对应的 taxonomy:
if (is_tax('your_custom_taxonomy')) { $current_term = get_queried_object(); $args['tax_query'] = array( array( 'taxonomy' => 'your_custom_taxonomy', 'field' => 'term_id', 'terms' => $current_term->term_id, ) ); }
内容的提问来源于stack exchange,提问作者shelleyn
相关产品推荐
相关产品推荐

