如何在WordPress中查询获取指定分类法下的文章?
WordPress 提取指定分类法下的文章解决方案
问题说明
你当前的代码仅获取了eposd_category分类法下的所有分类术语(比如分类、标签),并没有查询这些术语关联的文章。要实现提取指定分类法下的文章,需要用WP_Query构建文章查询逻辑。
修正后的代码示例
场景1:展示分类法下所有术语的关联文章
如果需要遍历该分类法下的每个术语,并展示对应术语下的所有文章,可使用以下代码:
<?php $taxonomy = 'eposd_category'; // 获取分类法下有文章的术语(hide_empty设为true过滤空术语) $terms = get_terms(array( 'taxonomy' => $taxonomy, 'hide_empty' => true, )); if ($terms && !is_wp_error($terms)) : foreach ($terms as $term) : // 查询当前术语下的文章 $post_query_args = array( 'post_type' => 'post', // 若用自定义文章类型,替换为对应名称 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $term->slug, ), ), 'posts_per_page' => -1, // 显示所有文章,可改为固定数字(如6)限制数量 ); $term_posts = new WP_Query($post_query_args); if ($term_posts->have_posts()) : ?> <div class="category-section"> <h2><?php echo $term->name; ?></h2> <div class="row"> <?php while ($term_posts->have_posts()) : $term_posts->the_post(); ?> <div class="col-sm-3"> <div class="post-card"> <?php if (has_post_thumbnail()) : ?> <div class="post-thumb"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </div> <?php endif; ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p><?php the_excerpt(); ?></p> </div> </div> <?php endwhile; ?> </div> </div> <?php wp_reset_postdata(); // 重置查询,避免影响后续全局文章数据 endif; endforeach; endif; ?>
场景2:仅提取单个指定术语下的文章
如果只需要展示该分类法下某一个特定术语的文章,直接指定术语slug即可:
<?php $taxonomy = 'eposd_category'; $target_term_slug = 'your-target-term-slug'; // 替换为你要查询的术语slug $post_query_args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $target_term_slug, ), ), 'posts_per_page' => 6, // 自定义显示文章数量 ); $term_posts = new WP_Query($post_query_args); if ($term_posts->have_posts()) : while ($term_posts->have_posts()) : $term_posts->the_post(); ?> <div class="col-sm-3"> <div class="post-card"> <?php if (has_post_thumbnail()) : ?> <div class="post-thumb"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </div> <?php endif; ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p><?php the_excerpt(); ?></p> </div> </div> <?php endwhile; wp_reset_postdata(); endif; ?>
原代码的小错误修正
你原代码中z_taxonomy_image($lug term->term_s)存在语法错误,正确写法应为z_taxonomy_image($term->term_id)(如果该函数需要传入术语ID的话)。
内容的提问来源于stack exchange,提问作者joumana fathi
相关产品推荐
相关产品推荐

