在 wordpress 中显示 post 的类别名称作为短代码的一部分
Display post's category name as a part of shortcode in wordpress
我正在尝试显示 post 的类别名称,但它不起作用。
我怎样才能让它工作?
我在 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');
尝试添加
$category = get_category($getpost->cat_ID)
然后替换
$getpost->cat_ID
至
$category->name
get_posts() 函数 returns post 不包含分类信息的对象数组。
正如@condini-mastheus 正确指出的那样,您需要使用 get_the_category() 来获取每个 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');
我正在尝试显示 post 的类别名称,但它不起作用。 我怎样才能让它工作? 我在 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');
尝试添加
$category = get_category($getpost->cat_ID)
然后替换
$getpost->cat_ID
至
$category->name
get_posts() 函数 returns post 不包含分类信息的对象数组。
正如@condini-mastheus 正确指出的那样,您需要使用 get_the_category() 来获取每个 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');