0

I want to display a list of categories after the first post in the Loop of index.php (this is the template my WP theme uses to display posts).

I've searched around on the web and found some code (see below) which is supposed to do as I want - inject a list of category titles as links between a list of posts in the Loop.

However, it is not working as expected. It only shows one category title, not all of them. Interestingly, it displays the title of the first post's category, but no others.

My Loop code, including the custom code I inserted, is as follows:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php get_template_part('content'); ?>

<div>

<?php 
 if( $wp_query->current_post == 0 ) { 

   $categories = get_the_category();
   $separator = ' ';
   $output = '';
   if($categories){
     foreach($categories as $category) {
       $output .= '<a href="'.get_category_link( $category ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
     }
     echo trim($output, $separator);
   }
} 

?>

</div>

<?php endwhile; ?>

Hoping someone can help.

Thanks,

Mekong

2

get_the_category() retrieves the current post categories. To get all categories you should use get_categories() instead

1
  • Yes, that worked! Many thanks, much appreciated!
    – Mekong
    Jan 15 '20 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.