-2

I have a wordpress page where I want am showing the latest 3 blog posts with a function. It's the following, and inside the div "blog-post", I'd like to display in which blog category each of the posts is. I've tried the function "get_the_category()" but it does not work for me, all the other 3 functions work just fine! Any tips?

Tried the following function, but it does only show 1 blog post category, not all (when a post has 2 categories selected, it only shows 1)

<?php echo wp_get_post_terms(get_the_ID(), 'category')[0]->name; ?>
<?php 
$the_query = new WP_Query( 'posts_per_page=3' ); ?>

<?php 
while ($the_query -> have_posts()) : $the_query -> the_post(); 
?>
            
<div class="blog-post">
<?php echo get_the_post_thumbnail( $the_query->ID, array( 400, 0) ); ?>
<?php echo get_avatar( get_the_author_meta( 'ID') , 150); ?>
<?php echo get_the_author_meta('display_name', $author_id); ?>
</div>

<?php 
endwhile;
wp_reset_postdata();
?>
FI_124
  • 21
  • 1
  • 4
  • _"but it does not work for me"_ - that does not work for us, as a problem description. Show what you tried, and give a proper explanation of what the problem is. – CBroe Apr 19 '22 at 13:35
  • I've tried adding the post categories but it does not show anything – FI_124 Apr 19 '22 at 13:36
  • With that last comment, you are basically just repeating what you already told us. What part of _show what you tried_ is unclear? – CBroe Apr 19 '22 at 13:38
  • 1
    Added to my post what I've tried! – FI_124 Apr 19 '22 at 13:44
  • You got an array - so, loop over it ...? https://stackoverflow.com/questions/9816889/how-to-echo-or-print-an-array-in-php – CBroe Apr 19 '22 at 13:45
  • 1
    I'm not a wordpress and php expert and it's been years since I used the platform, but that `name; ?>` should probably go inside of your `
    ` and should pass in the `id` of the current post you are iterating through in your while loop: like `ID, 'category')[0]->name; ?>` Perhaps paste that at the end of your other `
    – JNevill Apr 19 '22 at 13:52

1 Answers1

0

Instead of using get_the_category try using the_category.

To get comma separated list

 <?php echo the_category(', '); ?>
Dotsquares
  • 755
  • 1
  • 2
  • 10