wordpress面包屑导航制作教程(非插件)


面包屑导航(Breadcrumbs)是网页导航设计中一个标准设计模式,在网站浏览中非常有用。
在wordpress主题开发过程中,在文章页面或者独立页面经常需要添加面包屑导航来优化网站得SEO,众多SEOer一致认为,给网站添加面包屑导航有利于提高访客体验和搜索引擎优化,所以大多数网站都设计了面包屑导航。
先看看显示效果:
031101
wordpress面包屑导航制作方法如下:
1、在你当前主题的functions.php文件添加如下代码:

  1. function get_breadcrumbs()
  2. {
  3. global $wp_query;
  4. if ( !is_home() ){
  5. // Start the UL
  6. echo '<ul class="breadcrumbs">';
  7. // Add the Home link
  8. echo '<li><a href="'. get_settings('home') .'">'. get_bloginfo('name') .'</a></li>';
  9. if ( is_category() )
  10. {
  11. $catTitle = single_cat_title( "", false );
  12. $cat = get_cat_ID( $catTitle );
  13. echo "<li> &raquo; ". get_category_parents( $cat, TRUE, " &raquo; " ) ."</li>";
  14. }
  15. elseif ( is_archive() && !is_category() )
  16. {
  17. echo "<li> &raquo; Archives</li>";
  18. }
  19. elseif ( is_search() ) {
  20. echo "<li> &raquo; Search Results</li>";
  21. }
  22. elseif ( is_404() )
  23. {
  24. echo "<li> &raquo; 404 Not Found</li>";
  25. }
  26. elseif ( is_single() )
  27. {
  28. $category = get_the_category();
  29. $category_id = get_cat_ID( $category[0]->cat_name );
  30. echo '<li> &raquo; '. get_category_parents( $category_id, TRUE, " &raquo; " );
  31. echo the_title('','', FALSE) ."</li>";
  32. }
  33. elseif ( is_page() )
  34. {
  35. $post = $wp_query->get_queried_object();
  36. if ( $post->post_parent == 0 ){
  37. echo "<li> &raquo; ".the_title('','', FALSE)."</li>";
  38. } else {
  39. $title = the_title('','', FALSE);
  40. $ancestors = array_reverse( get_post_ancestors( $post->ID ) );
  41. array_push($ancestors, $post->ID);
  42. foreach ( $ancestors as $ancestor ){
  43. if( $ancestor != end($ancestors) ){
  44. echo '<li> &raquo; <a href="'. get_permalink($ancestor) .'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a></li>';
  45. } else {
  46. echo '<li> &raquo; '. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</li>';
  47. }
  48. }
  49. }
  50. }
  51. // End the UL
  52. echo "</ul>";
  53. }
  54. }

2、在需要使用到的面包屑导航页面位置添加以下调用代码:

  1. <?php
  2. if (function_exists('get_breadcrumbs')){
  3. get_breadcrumbs();
  4. }
  5. ?>

3.在主题的css样式文件中添加以下样式代码:

  1. ul.breadcrumbs {
  2. list-style: none;
  3. padding: 0;
  4. margin: 0;
  5. font-size:12px;
  6. }
  7. ul.breadcrumbs li {
  8. float: left;
  9. margin: 0 5px 0 0;
  10. padding: 0;
  11. }