LaVOZs

The World’s Largest Online Community for Developers

'; php - Insert content after first post in WordPress loop - LavOzs.Com

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 (the post that comes before the custom code), 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'); ?>

// START CUSTOM CODE

<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>

// END CUSTOM CODE

<?php endwhile; ?>  

Hoping someone can help.

Thanks,

Mekong

It is a little unclear to me from your question, but it seems like you want a list of all categories, correct? I think the line "$categories = get_the_category();" is getting categories for the current (in this case first) post only.

If you want a list of all categories that exist in your blog/website try 'get_categories', https://developer.wordpress.org/reference/functions/get_categories/

Try this code, small change in your code...

 <?php if (have_posts()) : $i = 1; while (have_posts()) : the_post(); ?>

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

<div class="categories">

<?php 
if( $i == 1){

    $categories = get_categories( array(
        'orderby' => 'name',
        'parent'  => 0
    ) );

    foreach ( $categories as $category ) {
        printf( '<a href="%1$s">%2$s</a><br />',
            esc_url( get_category_link( $category->term_id ) ),
            esc_html( $category->name )
        );
    }
}
?>

</div>


<?php $i++; endwhile; ?>  
Related
How to determine the first and last iteration in a foreach loop?
Looping through the content of a file in Bash
add a page to sidebar
PHP displaying Wordpress array.
WordPress trigger standard post list rendering
Wordpress Custom post type list categories & list post of active category
How loop through Custom Post Types and get their content in one page
Combine and display blog post result combined with custom taxonomy