• 首页
  • >
  • Notes
  • >
  • WordPress面包屑导航实现(非插件)
  • WordPress面包屑导航实现(非插件)

    Time:2020-03-03 / View:532

    据说,面包屑导航有利于SEO,所以在开发本站主题的时候也加入了面包屑导航功能。

    请将如下函数放入主题的function.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>';  
        
            if ( is_category() )  
            {  
                $catTitle = single_cat_title( "", false );  
                $cat = get_cat_ID( $catTitle );  
                echo " &raquo; ". get_category_parents( $cat, TRUE, " &raquo; " ) ."</li>";  
            }  
            elseif ( is_archive() && !is_category() )  
            {  
                echo " &raquo; Archives</li>";  
            }  
            elseif ( is_search() ) {  
        
                echo " &raquo; Search Results</li>";  
            }  
            elseif ( is_404() )  
            {  
                echo " &raquo; 404 Not Found</li>";  
            }  
            elseif ( is_single() )  
            {  
                $category = get_the_category();  
                $category_id = get_cat_ID( $category[0]->cat_name );  
        
                echo ' &raquo; '. get_category_parents( $category_id, TRUE, " &raquo; " );  
                echo the_title('','', FALSE) ."</li>";  
            }  
            elseif ( is_page() )  
            {  
                $post = $wp_query->get_queried_object();  
        
                if ( $post->post_parent == 0 ){  
        
                    echo " &raquo; ".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 ' &raquo; <a href="'. get_permalink($ancestor) .'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a></li>';  
                        } else {  
                            echo ' &raquo; '. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</li>';  
                        }  
                    }  
                }  
            }  
        
            // End the UL  
            echo "</ul>";  
        }  
    }  

    调用方法:

    找到主题的文章模板single.php文件,在while ( have_posts() ) :前面加上如下代码即可:

    if (function_exists('get_breadcrumbs')){get_breadcrumbs(); }

    发布留言