显示 wordpress 类别名称和相关帖子

Display wordpress category name and the related posts

我想在顶部显示类别名称,然后在其下方显示属于特定类别的帖子。

这应该适用于我的所有 20 个类别,并且结果显示在一页上。

这是我尝试过的方法,但没有用。

<?php $catquery = new WP_Query( 'cat=finance-training-seminars&posts_per_page=-1&post-type=dt_portfolio' ); ?>
<ul>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>

<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>

<?php endwhile; ?> 
</ul>
<?php wp_reset_postdata(); ?> 

您可以使用 get_terms 列出所有类别,然后为每个类别创建一个查询并显示与其相关的帖子,如下所示:

<?php
$categories = get_terms( array( 'taxonomy' => 'category' ) );
foreach( $categories as $cat ) :
    $posts = new WP_Query( array(
        'post_type'     => 'dt_portfolio',
        'showposts'     => -1,
        'tax_query'     => array(
                               array(
                                   'taxonomy' => 'category',
                                   'terms'    => array( $cat->term_id ),
                                   'field'   => 'term_id'
                               )

                          )
    ) ); ?>

    <h3><?php echo $cat->name; ?></h3>

    <ul>
        <?php while( $posts->have_posts() ) : $posts->the_post(); ?>
            <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>

<?php endforeach; ?> 

试试这个,

    <?php 
      $rCateogry = get_the_terms( $post->ID, 'CUSTOM_TAXONOMY_NAME' ); 
      $related = get_posts(array( 'post_type' => 'CUSTOM_POST_TYPE',  'tax_query' => array(array(  'taxonomy' => 'CUSTOM_TAXONOMY_NAME', 'field'    => 'id', 'terms'    => $rCateogry, )), 'showposts' => -1, 'order' => 'DESC', 'post__not_in' => array($post->ID) )); ?>
  <section id="discover">
    <h2>Related Posts</h2>
      <div class="singlepost">
        <?php if( $related ) foreach( $related as $post ) {
          setup_postdata($post); ?>
            <h4><?php the_title(); ?></h4>
                <?php the_excerpt(); ?>
                <?php $cats = array();
                foreach($rCateogry as $c){
                    $cat = get_category( $c );
                    echo $cat->name;
                } ?>
        <?php } 
      wp_reset_postdata(); ?>
      </div>
  </section>

将 "CUSTOM_TAXONOMY_NAME" 替换为分类名称,将 "CUSTOM_POST_TYPE" 替换为 post 类型名称