Unable to display category name of post

On my home page, I’m trying to loop through a set number of posts and display the category name of each post. The category that I’m trying to display the name for is a subcategory of a parent (if that makes any difference). Here’s my code for it:

            <?php 
                $args = array( 'numberposts' => '15' );
                $recent_posts = wp_get_recent_posts( $args ); 
                foreach ( $recent_posts as $recent ) {
                    $category = get_the_category($recent['ID']);
                    echo $category['cat-name'];
            }; ?>

When I run that, nothing ends up displaying. That page displays as if the code wasn’t there. But when I do a var_dump on $category:

            <?php 
                $args = array( 'numberposts' => '15' );
                $recent_posts = wp_get_recent_posts( $args ); 
                foreach ( $recent_posts as $recent ) {
                    $category = get_the_category($recent['ID']);
                    echo var_dump($category);
            }; ?>

I can see that everything is there that I need. Each post, with it’s keys and values, but for some reason trying to display a specific property of a post (like ‘cat-name’, or even ‘name’) doesn’t work. Any ideas?

Can you show the result of the var_dump() in case it helps diagnose the issue?

Sure thing, I edited some of the strings out, but they were just strings of course:

array (size=1)
0 =>
object(WP_Term)[1339]
public ‘term_id’ => int 41
public ‘name’ => string ‘{edited}’ (length=13)
public ‘slug’ => string ‘{edited}’ (length=13)
public ‘term_group’ => int 0
public ‘term_taxonomy_id’ => int 41
public ‘taxonomy’ => string ‘category’ (length=8)
public ‘description’ => string ‘’ (length=0)
public ‘parent’ => int 14
public ‘count’ => int 3
public ‘filter’ => string ‘raw’ (length=3)
public ‘cat_ID’ => int 41
public ‘category_count’ => int 3
public ‘category_description’ => string ‘’ (length=0)
public ‘cat_name’ => string ‘{edited}’ (length=13)
public ‘category_nicename’ => string ‘{edited}’ (length=13)
public ‘category_parent’ => int 14

I actually figured it out. My syntax was wrong, i need to do:

echo $category[0]->name;

Simple fix, but certainly spent a lot of time finding it. Thanks.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.