非插件实现WordPress面包屑导航的方法

NOCO发布于 来源 原文链接

8天前 有1个用户阅读过

"面包屑导航"缘自于童话故事,面包屑导航的作用是告诉访问者他们目前在网站中的位置以及如何返回。众多SEOer一致认为,给网站添加面包屑导航有利于提高访客体验和搜索引擎优化,所以大多数网站都设计了面包屑导航。对wordpress添加面包屑导航有插件和非插件两种方法,下面博客吧介绍非插件实现wordpress面包屑导航。
不用插件实现wordpress面包屑导航:

1.在wordpress博客当前主题的functions.php文件(没有就创建一个)中添加以下代码:

//面包屑导航
function get_breadcrumbs()
{
  global $wp_query; 
  if ( !is_home() ){ 
    // Start the UL
    echo '<ul class="breadcrumbs">';
    // Add the Home link
    echo '<li><a href="'. get_settings('home') .'">'. get_bloginfo('name') .'</a></li>'; 
    if ( is_category() )
    {
      $catTitle = single_cat_title(", false );
      $cat = get_cat_ID( $catTitle );
      echo"<li> »". get_category_parents( $cat, TRUE," »" ) ."</li>";
    }
    elseif ( is_archive() && !is_category() )
    {
      echo"<li> » Archives</li>";
    }
    elseif ( is_search() ) { 
      echo"<li> » Search Results</li>";
    }
    elseif ( is_404() )
    {
      echo"<li> » 404 Not Found</li>";
    }
    elseif ( is_single() )
    {
      $category = get_the_category();
      $category_id = get_cat_ID( $category[0]->cat_name ); 
      echo '<li> » '. get_category_parents( $category_id, TRUE," »" );
      echo the_title('','', FALSE) ."</li>";
    }
    elseif ( is_page() )
    {
      $post = $wp_query->get_queried_object(); 
      if ( $post->post_parent == 0 ){ 
        echo"<li> »".the_title('','', FALSE)."</li>"; 
      } 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 '<li> » <a href="'. get_permalink($ancestor) .'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a></li>';
          } else {
            echo '<li> » '. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</li>';
          }
        }
      }
    } 
    // End the UL
    echo"</ul>";
  }
}
2.在显示面包屑导航的位置添加以下调用代码
<?php
if (function_exists('get_breadcrumbs')){
  get_breadcrumbs();
}
?>
3.在主题的css样式文件中添加以下样式代码
ul.breadcrumbs {list-style: none; font-size:12px;}
ul.breadcrumbs li {float: left; margin-right:5px;}
4.添加完成后,就可以显示面包屑导航的效果了。

-- The End --

本文标题: 非插件实现WordPress面包屑导航的方法

本文地址: https://seonoco.com/blog/wordpress-creating-breadcrumbs-without-a-plugin

原文地址: http://www.boke8.net/wordpress-breadcrumb-navigation.html

本文是否有所帮助?
点赞 0
感谢支持
0
多谢反馈
评论 0
打赏

支持微信/支付宝

评论

网友