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


 if( $wp_query->current_post == 0 ) { 

   $categories = get_the_category();
   $separator = ' ';
   $output = '';
     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);



<?php endwhile; ?>

Hoping someone can help.



1 Answer 1


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

  • Yes, that worked! Many thanks, much appreciated!
    – Mekong
    Commented Jan 15, 2020 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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