如何调用WordPress父子分类目录
以下代码由PHP站长网 52php.cn收集自互联网现在PHP站长网小编把它分享给大家,仅供参考 相信有很多使用 wordpress 模板的博友,把分类目录列表显示在博客首页,有利于提高用户体验。WordPress 经常用到的博客分类目录调用函数是 wp_list_cats,对于该函数,普通博主可能只会简单地应用,其实通过给它设置不同的参数,可以显示不同的分类目录列表的效果。在当前分类或者正文页面想调用显示与当前分类存在父子关系的分类目录时会用到。 代码一:将下面代码加到主题模板适当位置,比如侧边栏: // CSS样式可以自己修改 <style>.crumbs_wrap #cat_list{border-top: 1px #eee solid;margin: 20px -20px 0;padding: 20px 0 0;}.crumbs_wrap ul{text-align: left;}</style> <?php $current = ""; if(is_single()){ $parent = get_the_category(); $parent = $parent[0]; $current = "¤t_category=".$parent->term_id; }else if(is_category()){ global $cat; $parent = get_category($cat); } if($parent->category_parent != 0){ $cat_id = $parent->category_parent; $parent = get_category($cat_id); if($parent->category_parent != 0){ $cat_id = $parent->category_parent; }else{ $cat_id = $parent->term_id; } }else{ $cat_id = $parent->term_id; } ?> <?php if(!is_page()) { ?> <h3><?php echo $parent->cat_name; ?><span><?php echo $parent->slug; ?></span></h3> <ul id="cat_list"> <?php wp_list_categories("title_li=&child_of=$cat_id".$current); ?> </ul> <?php } ?> 代码二:将下面代码加到主题 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号 } 调用显示代码加到主题模板的适当位置: <?php if(is_category()) { if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" ) { echo '<ul>'; echo wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC"); echo '</ul>'; } } ?> 显示 WordPress 父子分类目录当需要显示文章的父分类和当前分类链接时,我们可以使用这段代码: $categories = get_the_category(); echo '<ul>'; echo '<li> Parent Category: '; foreach( $categories as $category ){ if($category->parent != 0){ $parent_category = get_term( $category->parent ); echo '<a href="' . esc_url( get_category_link($parent_category->term_id)) . '">' . esc_html($parent_category->name) . ' </a>'; break; } } echo '</li>'; echo '<li>Subcategory: '; foreach( $categories as $category ){ if($category->parent != 0){ echo '<a href="' . esc_url( get_category_link($category->term_id)) . '">' . esc_html($category->name) . ' </a>'; } } echo '</li></ul>'; 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |