广告投放

调用WordPress父子分类目录

目录

    调用WordPress父子分类目录
    WordPress

    WordPress当前分类或者正文页面,想调用显示与当前分类存在父子关系的分类目录时,会用到。

    如:一个分类页面,想显示出自己的上级分类

    代码一:

    将下面代码加到主题模板适当位置,比如侧边栏:

    <?php
        $current = "";
        if(is_single()){
            $parent = get_the_category();
            $parent = $parent[0];
            $current = "&current_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>';
            }
        }
    ?>

    原文地址:www.5che2.com

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

    给TA打赏
    共{{data.count}}人
    人已打赏
    广告位招租919838898
    0 条回复 A文章作者 M管理员
      暂无讨论,说说你的看法吧
    个人中心
    购物车
    优惠劵
    今日签到
    有新私信 私信列表
    搜索