• Resolved 4davidk

    (@4davidk)


    Hello all.

    I am working on a project for my company building a word press template. On the single.php page, they would like at the end of the post a section that would basically display the next post in line, so a link that says “Read what’s next” followed by the posts categories, the title and the excerpt. I have every working, but the categories, I have tried and searched for hours to find out how to do this, is it possible? my code below:

    <div class="entrynext">
          <div class="whats-next">
            <?php next_post_link( '%link', "Read What's Next »"); ?>
            </a></div>
    
            <?php
    $next_post = get_next_post();
    if (!empty( $next_post )): ?>
    
          <div class="categoryHeader">
    
    	Categories should display here
    
          </div>
          <h3> <a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo $next_post->post_title; ?></a>
          </h3>
          <div class="entry-content">
            <div class="entry-excerpt">
              <h4>
               <?php echo $next_post->post_excerpt; ?>
              </h4>
            </div>
    
            <!-- .entry-excerpt --> 
    
          </div>
          <?php endif; ?>
          <!-- .entry-content -->

    Thanks 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • use below code

    <div class="categoryHeader">
        <?php
            $nextpostid = $next_post->ID;
            echo get_the_category_list(', ','',$nextpostid);
        ?>
    </div>

    Thread Starter 4davidk

    (@4davidk)

    THANK YOU SO MUCH SWAYAM! This worked perfectly, another thing I just realized is that I need to exclude 3 categories, any hints on how to do that with this loop?

    Thanks again.

    so, you need to change the code, as now you need to exclude some categories, use code below

    <div class="categoryHeader">
    
    <?php
    $next_post = get_next_post();
    $nextpostid = $next_post->ID;
    
    $exclude_cats = array(6,7,8);
    
    $allcats = get_the_category($nextpostid);
    
    $numItems = count($allcats);
    $i = 0;
    $catstr = '';
    foreach($allcats as $allcat){
    
    	if(!in_array($allcat->term_id,$exclude_cats)){
    
    		$catlink = get_category_link( $allcat->term_id );
    
    		$catstr .= '<a href="'.$catlink.'">'.$allcat->name.'</a>, ';
    
    	}
    
    }
    
    echo rtrim($catstr,', ');
    
    ?>
    </div>

    the line where it says “$exclude_cats = array(6,7,8);”
    you need to pass id of categories you want to exlude from the list, let me know if it works.

    Thread Starter 4davidk

    (@4davidk)

    It works very well, thank you so much, hours and hours of looking online.

    Glad it works for you, happy to help 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Getting the categories from the next post to display’ is closed to new replies.