wordpress 面包屑导航

后端 2019-11-18T10:49:11 浏览:137

面包屑导航(BreadcrumbNavigation)这个概念来自童话故事”汉赛尔和格莱特”,当汉赛尔和格莱特穿过森林时,不小心迷路了,但是他们发现在沿途走过的地方都撒下了面包屑,让这些面包屑来帮助他们找到回家的路。所以,面包屑导航的作用是告诉访问者他们目前在网站中的位置以及如何返回。

1.在functions.php中添加面包屑导航函数

function the_breadcrumb() {
    global $wp_query;
    echo '<a href="/">' . '首页' . '</a>';
    if (is_category()) {
        $catTitle = single_cat_title("", false);
        $cat = get_cat_ID($catTitle);
        echo ' <span></span> ' . get_category_parents($cat, TRUE, ' <span></span> ') . '';
    } elseif (is_archive() && !is_category()) {
        echo ' <span></span> 归档</li>';
    } elseif (is_search()) {
        echo ' <span></span> 搜索结果';
    } elseif (is_404()) {
        echo ' <span></span> 404 Not Found';
    } elseif (is_single()) {
        $category = get_the_category();
        $category_id = get_cat_ID($category[0]->cat_name);
        echo ' <span></span> ' . get_category_parents($category_id, TRUE, ' <span></span> ');
        echo the_title('', '', FALSE) . '</li>';
    } elseif (is_page()) {
        $post = $wp_query->get_queried_object();
        if ($post->post_parent == 0) {
            echo ' <span></span> ' . the_title('', '', FALSE) . '';
        } else {
            $title = the_title('', '', FALSE);
            $ancestors = array_reverse(get_post_ancestors($post->ID));
            array_push($ancestors, $post->ID);
            foreach ($ancestors as $ancestor) {
                if ($ancestor != end($ancestors)) {
                    echo ' <span></span> <a class="breadcrumbs__url" href="' . get_permalink($ancestor) . '">' . strip_tags(apply_filters('single_post_title', get_the_title($ancestor))) . '</a>';
                } else {
                    echo '<span></span> ' . strip_tags(apply_filters('single_post_title', get_the_title($ancestor))) . '';
                }
            }
        }
    }
}

2.在有需要添加面包屑插件的页面适当位置添加

<php get_breadcrumbs(); >

3.输出面包屑导航代码

<a href="/">首页</a> <span></span> <a href="/category/news/">新闻中心</a> <span></span> <a href="/category/news/information/">行业资讯</a> <span></span> html+css+js教程

样式文件自由发挥!