Skip to content

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 want to add breadcrumb to your WordPress theme, then you’ll need to add the following snippet to your WordPress website:

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();
        }
    }
}Code language: PHP (php)

Next, you’ll need to add the following code inside your theme files, where you want to display the breadcrumbs (usually single.php and page.php files):

<?php tp_breadcrumbs(); ?>Code language: HTML, XML (xml)

If you’re not satisfied with the above breadcrumbs code, you can also add the following snippet, 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();
        }
    }
}Code language: PHP (php)

Leave a Reply

Your email address will not be published. Required fields are marked *