简体   繁体   中英

Display wordpress category name and the related posts

I want to display category name on top and then the posts belonging to the particular category below it.

This should happen for all of my 20 categories and the results show be displayed on one page.

This is something I was trying but it doesn't work.

<?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(); ?> 

You can use get_terms to list all categories and then create a query for each category and show posts related to it, something like this:

<?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; ?> 

Try this,

    <?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>

Replace "CUSTOM_TAXONOMY_NAME" with the taxonomy name and "CUSTOM_POST_TYPE" with post type name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM