display categories in index php wordpress

    By: Manu
    3 years ago

    display categories in index php wordpress

    Here is the working solution

    if(have_posts()):
    
            while(have_posts()):the_post();
            ?>
                <article class="post">
                        <a href="<?php the_permalink(); ?>">
                            <h2>
                                <?php the_title();  ?>
                            </h2>
                        </a>
                        
                        <small>
                            <?php
                                $categories = get_the_category();
                                $separator = ", ";
                                $output = '';
    
    
    
                                
                                if($categories){
                                    for( $i= 0; $i<count($categories); $i++){
                                        $output .= '<a href="'.get_category_link($categories[$i]->term_id).'">'.$categories[$i]->name.'</a>'.$separator;
                                    }
                                }
                                echo trim($output,$separator);
                            ?>
                        </small>
    
    
                        <p>
                            <?php the_content();  ?>
                        </p>
                </article>
            <?php
            endwhile;
        
    else :
    
            echo "No Posts Found";
    
    endif;