在WordPress中将帖子的类别名称显示为短代码的一部分

我正在尝试显示帖子的类别名称, 但是它不起作用。我该如何工作?我在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

来源:

https://www.srcmini02.com/64993.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_37362.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?