我正在尝试显示帖子的类别名称, 但是它不起作用。我该如何工作?我在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');
#1
get_posts()函数返回不包含有关分类法信息的post对象数组。
正如@ condini-mastheus正确指出的那样, 你需要使用get_the_category()来获取每个帖子的类别:
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');
#2
尝试添加
$category = get_category($getpost->cat_ID)
并且比替换
$getpost->cat_ID
to
$category->name
评论前必须登录!
注册