如何在 WordPress 中显示分类术语的帖子列表?

How to display a list of posts from a taxonomy term in WordPress?

我想创建一个这样的列表:

分类术语名称
- Post 1
- Post 2
- Post 3

至此,我迈出了第一步。这是代码:

$term_list = wp_get_post_terms(
        $post->ID,
        'job_listing_category',
        array( 'fields' => 'all' )

    );

这是获取分类术语。第一步完成。但是我如何做类似的事情并从该分类法中获取列表呢?

如果是自定义分类术语你可以试试:

<?php
$custom_terms = get_terms('post-terms-type');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'post-type',
    'tax_query' => array(
        array(
            'taxonomy' => 'post-terms-type',
            'field' => 'slug',
            'terms' => $custom_term->slug,
        ),
    ),
 );
 $loop = new WP_Query($args);
 if($loop->have_posts()) {
    echo '<h2 class="terms-title">'.$custom_term->name.'</h2>';
    echo '<ul class="post-list">';
    while($loop->have_posts()) : $loop->the_post();
        echo '<li><a href="'.get_permalink().'" title="'.get_the_title().'" target="_blank">'.get_the_title().'</a></li>';
    endwhile;
    echo "</ul>";
 }
}
  ?>

您可以使用 get_posts() 轻松做到这一点,如下所示:

    foreach ($term_list as $term) {
        $posts = get_posts( [
            'numberposts' => 1,
            'category' => $term->ID,
        ] );

        foreach ( $posts as $post ) {
            echo $post->post_title;
        }
    }