Hirohito Yamada
Hirohito Yamada

Reputation: 387

Display post's category name as a part of shortcode in wordpress

I'm trying to display post's category name but it's not working. How could I get this to work? I've wrote the following in function.php

function wptuts_recentpost2($atts, $content=null){
$getpost = get_posts( array('number' => 1, 'offset' => 1) );
$getpost = $getpost[0];
$return = get_the_post_thumbnail($getpost->ID) . "<br /><a class='post_title' href='" . get_permalink($getpost->ID) . "'>" . $getpost->post_title . "</a>.$getpost->cat_ID. <br />" . $getpost->post_excerpt . "…";
$return .= "<br /><br />"; 
return $return;
}
add_shortcode('newestpost2', 'wptuts_recentpost2');

Upvotes: 0

Views: 909

Answers (2)

cabrerahector
cabrerahector

Reputation: 3948

The get_posts() function returns an array of post objects which don't include info on their taxonomies.

As @condini-mastheus correctly points out, you'll need to use get_the_category() to obtain the category of each post:

function wptuts_recentpost2( $atts, $content=null ){

    $getpost = get_posts( array('number' => 1, 'offset' => 1) );
    $getpost = $getpost[0];
    $category = get_the_category( $getpost->ID );

    $return = get_the_post_thumbnail($getpost->ID) . "<br /><a class='post_title' href='" . get_permalink($getpost->ID) . "'>" . $getpost->post_title . "</a>" . $category[0]->cat_name . "<br />" . $getpost->post_excerpt . "…";
    $return .= "<br /><br />";

    return $return;

}
add_shortcode('newestpost2', 'wptuts_recentpost2');

Upvotes: 1

theebigbang
theebigbang

Reputation: 66

Try to add

$category = get_category($getpost->cat_ID)

and than replace

$getpost->cat_ID

to

$category->name

Upvotes: 0

Related Questions