admin管理员组

文章数量:1404625

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

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

Share Improve this question asked Jan 15, 2020 at 0:05 MekongMekong 1032 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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

本文标签: phpAdd content after the first post in WP Loop