最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Add content after the first post in WP Loop

programmeradmin5浏览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

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

发布评论

评论列表(0)

  1. 暂无评论