How to show only one category in breadcrumb navigation

I added breadcrumb navigation to WordPress & I’m facing one problem. Here’s the function.php code of the breadcrumb:

function ux_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();
        }
    }
}

The above code is displaying all categories of the post. I just want it to display only one category. Thanks in advance!

Read More

UPDATE: Thanks for the help…here’s one more thing:

I want to know how to display category > sub category in the breadcrumb if exists.

Related posts

1 comment

  1. get_the_category() function used to retrieve categories array of a post, and array_shift() function used to get the first item of an array.

    You possibly need this –

    function ux_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() )
                {
                    echo " » ";
                    $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();
            }
        }
    }
    

Comments are closed.