Search code examples
phpwordpresswordpress-themingcustom-wordpress-pages

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');

Solution

  • 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');