How To Add Breadcrumbs To WordPress

Breadcrumbs navigation is a menu which helps users to keep track of their locations within the website. Breadcrumbs typically appear across the top of a website, or above the page title or headers. Typical breadcrumbs look like this:

Home page > Category > Post

Today, I’ll show you how to add breadcrumbs to WordPress blog without any additional plugin. There are lots of breadcrumbs tutorials on the internet, but all have the same problems. All of the breadcrumbs codes will show all categories in the navigation, but I always wanted a breadcrumbs which will only one category of the post in it.

If you wanna add breadcrumb to your WordPress theme, then add following snippet to your functions.php file:

function tp_breadcrumbs() {
    if (!is_home()) {
        echo '<a href="';
        echo get_option('home');
        echo '">';
        bloginfo('name');
        echo "</a> » ";
        if (is_category() || is_single() )
        {
            if( is_category() )
            {
                single_term_title();
            }
            elseif (is_single() )
            {
                $cats = get_the_category( get_the_ID() );
                $cat = array_shift($cats);
                echo '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $cat->name ) ) . '">'. $cat->name .'</a>';
                echo " » ";
                the_title();
            }
        } elseif (is_page()) {
            echo the_title();
        }
    }
}

Now, add following code to where you want to display the breadcrumbs (usually single.php and page.php files):

<?php tp_breadcrumbs(); ?>

If you’re not satisfied with the above breadcrumbs code, you can also add following code to functions.php file, which will show all categories in the breadcrumbs:

function tp_breadcrumbs() {
    if (!is_home()) {
        echo '<a href="';
        echo get_option('home');
        echo '">';
        bloginfo('name');
        echo "</a> » ";
        if (is_category() || is_single()) {
            the_category('/');
            echo " » ";
            if (is_single()) {
                echo "  ";
                the_title();
            }
        } elseif (is_page()) {
            echo the_title();
        }
    }
}

Leave a Comment