之所以要发这篇文章,是因为这个方法适用于:
- WP默认文章分类
- 手动添加的自定文章分类
- 插件(custom post type ui)添加的自定义文章分类(含taxonomy)
方法目的:在文章模板中,调用该模板的所有文章,可以获得当前文章所属分类的ID,名称。
方法实现:首先在主题的 functions.php 里添加:
/**
* 文章模板 single.php 获取当前文章所属的分类名称
* https://www.wpdaxue.com/get-post-category.html
*/
function get_post_category_id($post_ID){
global $wpdb;
$sql="SELECT `term_taxonomy_id` FROM $wpdb->term_relationships WHERE `object_id`='".$post_ID."';";
$cat_id=$wpdb->get_results($sql);
foreach($cat_id as $catId){
$output=$catId->term_taxonomy_id;
}
$myCatId=intval($output);//这里就获得当前文章所属分类的分类ID
$term = get_term( $myCatId, 'taxonomy_name' );//taxonomy_name为自己定义的或者默认的
echo $term->name;//得到当前文章所属分类的分类名称
} |
/**
* 文章模板 single.php 获取当前文章所属的分类名称
* https://www.wpdaxue.com/get-post-category.html
*/
function get_post_category_id($post_ID){
global $wpdb;
$sql="SELECT `term_taxonomy_id` FROM $wpdb->term_relationships WHERE `object_id`='".$post_ID."';";
$cat_id=$wpdb->get_results($sql);
foreach($cat_id as $catId){
$output=$catId->term_taxonomy_id;
}
$myCatId=intval($output);//这里就获得当前文章所属分类的分类ID
$term = get_term( $myCatId, 'taxonomy_name' );//taxonomy_name为自己定义的或者默认的
echo $term->name;//得到当前文章所属分类的分类名称
}
然后,在文章模板中,添加一句话即可:
<?php if(function_exists('get_post_category_id')) get_post_category_id(get_the_ID()); ?> |
<?php if(function_exists('get_post_category_id')) get_post_category_id(get_the_ID()); ?>
来源:
https://www.wpdaxue.com/get-post-category.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_32240.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57