面包屑导航对于用户体验和搜索引擎至关重要,之前我写过WordPress增加面包屑导航的最佳3个方案都是用插件的方式,如果不用插件怎么写?
将一下代码通过自定义代码的方式实现。
// functions.php function the_breadcrumb() { $post_ancestors = get_post_ancestors(get_the_ID()); echo '<nav aria-label="breadcrumb">'; echo '<ol class="breadcrumb">'; echo '<li class="breadcrumb-item"><a href="' . get_home_url() . '">Home</a></li>'; if (is_category()) { $category = get_category(get_query_var('cat')); echo '<li class="breadcrumb-item active" aria-current="page">' . $category->name . '</li>'; } elseif (is_tag()) { echo '<li class="breadcrumb-item active" aria-current="page">' . single_tag_title('', false) . '</li>'; } elseif (is_author()) { $author = get_user_by('slug', get_query_var('author_name')); echo '<li class="breadcrumb-item active" aria-current="page">' . $author->display_name . '</li>'; } elseif (is_page()) { if (!empty($post_ancestors)) { foreach ($post_ancestors as $post_ancestor_id) { $post_ancestor = get_post($post_ancestor_id); echo '<li class="breadcrumb-item"><a href="' . get_permalink($post_ancestor_id) . '">' . $post_ancestor->post_title . '</a></li>'; } } echo '<li class="breadcrumb-item active" aria-current="page">' . the_title() . '</li>'; } elseif (is_single()) { $categories = get_the_category(); if (!empty($categories)) { $category = $categories[0]; echo '<li class="breadcrumb-item"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>'; } echo '<li class="breadcrumb-item active" aria-current="page">' . the_title() . '</li>'; } echo '</ol>'; echo '</nav>'; }
在主题中用下面函数来实现:
// In your theme the_breadcrumb();
这里我们只考虑到了文章、页面、分类、作者、标签这5个类型的页面。其他页面来说,意义不大,甚至可以只考虑文章、页面这2个类型的页面。