wordpress在分类页获取当前分类id或在文章页获取获取所属分类id
我们在开发wordpress主题的时候经常要获取分类目录id,根据所在页面的位置获取分类id的方法各不一样下面由小编具体介绍。
1,在内配分类页面 category.php
a,全局变量$cat直接存储着当前的分类id
global $cat;
var_dump($cat);

b,通过get_query_var函数获取分类目录id
get_query_var('cat')
c,通过get_queried_object函数获取分类目录id
$cat_id = get_queried_object()->term_id;
echo $cat_id;
get_queried_object_id() //直接返回当前分类id
2,在自定义分类页面taxonomy或taxonomy-slug.php。slug是指自定义分类法名称,如我注册了一个叫”product_category”的自定义分类法。那文件名应该是taxonomy-product_category.php。
a,通过全局变量获取分类id
global $term; //分类的别名
global $taxonomy;//自定义分类法名称
$tterm_obj = get_term_by( 'slug', $term, $taxonomy );
$term_id = $tterm_obj->term_id;
b,通过get_queried_object函数获取分类id
get_queried_object()->term_id;
get_queried_object_id()
c,通过get_term_by函数获取分类id
$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;
var_dump($termId);
3,在普通文章页面 single.php
a,通过get_the_terms函数获取文章所属分类id
$term_id = get_the_terms($post,'category')[0]->term_id;
echo $term_id;
b,通过get_the_category获取文章所属id
$term_id = get_the_category()[0]->term_id;
echo $term_id;
4,在自定义文章类型页面 single-slug.php。slug是指自定义文章类型名称,假如我注册了一个叫”product”的自定义文章类型那文件名应是single-product.php
$taxonomies = get_the_taxonomies($post);
if ($taxonomies) {
$taxonomy = array_keys($taxonomies)[0];
$terms = get_the_terms($post->ID, $taxonomy);
echo $terms[0]->term_id;
}
好主题网专注于wordpress企业主题开发定制,本网站所展示和出售的主题均有好主题网原创开发。没有经过本网站书面许可下禁止任何形式的转载和二次销售本网站资源。
好主题 » wordpress在分类页获取当前分类id或在文章页获取获取所属分类id
好主题 » wordpress在分类页获取当前分类id或在文章页获取获取所属分类id