craigb88 craigb88 - 1 month ago 6
PHP Question

Display current posts category Wordpress

On my front-page.php I have a custom loop displaying all posts. I loop through them and display the featured image and title. I also want to add the category that the post is in but seem to be hitting a brick wall!
It's probably an easy fix but any help would be appreciated.

Here's my code.

<? $posts = get_posts();
foreach($posts as $post) : setup_postdata($post); ?>

<? global $post; $categories = get_the_category($post->ID);?>

<div class="col-sm-6 col-md-4">
<div <?php post_class( 'category-wrapper' ); ?>>
<div class="post-image">
<? if (has_post_thumbnail()) {
the_post_thumbnail();
} ?>
</div>
<div class="post-content">
<p class="title"><? the_title(); ?></p>
<p class="cat-title"><?= $categories['cat_name']; ?></p>
</div>
</div>
</div>

<? endforeach; wp_reset_postdata(); ?>


Thanks in advance :)

Answer

Here is the example:

<? $posts = get_posts(); 
foreach($posts as $post) : setup_postdata($post); ?>

    <? global $post; $categories = get_the_category($post->ID);?>

    <div class="col-sm-6 col-md-4">
        <div <?php post_class( 'category-wrapper' ); ?>>
            <div class="post-image">
                <? if (has_post_thumbnail()) {
                    the_post_thumbnail();
                } ?>
            </div>
            <div class="post-content">
                <p class="title"><? the_title(); ?></p>
                <? foreach( $categories as $category ): ?>
                    <p class="cat-title"><?= $category->cat_name; ?></p>
                <? endforeach; ?>
            </div>
        </div>
    </div>

<? endforeach; wp_reset_postdata(); ?>
Comments