现在位置: 首页 > CMS知识 > 正文

wordpress 调用指定分类下的子分类 实现方法

发布时间:2022 年 9 月 30 日

本文作者:帮建站

点击次数:877

1.首先在网站主题的函数模板function.php里添加以下代码:

//调用子分类、
function get_category_root_id($cat)
{
$this_category = get_category($cat); // 取得当前分类
while($this_category->category_parent) // 若当前分类有上级分类时,循环
{
$this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类(往上爬)
}
return $this_category->term_id; // 返回根分类的id号
}
2.然后在页面要显示子分类的地方(一般是在侧边栏)粘贴下面这段代码即可
<?php wp_list_cats('child_of=' . get_category_root_id($cat) . 
'&depth=1&hide_empty=0&hierarchical=1&optioncount=1');?>

如果想更灵活的调用当前分类下的子分类,可以使用下面的代码:
<?php
$args=array(
‘child_of’=> get_category_root_id($cat),
‘hide_empty’=>‘0’,
);
$categories=get_categories($args);
foreach($categories as $category) {
echo ‘<h3><a href=”‘ . get_category_link( $category->term_id ) . ‘” title=”‘ . sprintf( __( “View all posts in %s” ), $category->name ) . ‘” ‘ . ‘>’ . $category->name.‘</a></h3>’;
}
?>

                                        			

问题本身还是很简单的,只是对于不熟悉的网友来说不知道什么原因,如果英语不太好的话,就以为自己买了个假主题了。问题本身还是很简单的,只是对于不熟悉的网友来说不知道什么原因,如果英语不太好的话,就以为自己买了个假主题了。


首页 在线 手机