Quantcast
Channel: WordPress Cheat Sheets » admin
Viewing all articles
Browse latest Browse all 39

WordPress Breadcrumbs Code – Add Breadcrumbs to Your WordPress site

$
0
0

WordPress doesn’t have any option to enable or show breadcrumb on your site. In this tutorial I will show you how you can easily create a WordPress breadcrumb function and use it show breadcrumb on your site.

What is WordPress Breadcrumbs?

Breadcrumbs or breadcrumb trail is a navigation aid used in websites. It allows site visitors to keep track of their locations within the website. Here is an example of how a breadcrumb looks like in a WordPress site:

Wordpress breadcrumbs example

Step 1: How to Create a WordPress Breadcrumbs Function

Here is a custom WordPress breadcrumbs function that is capable of outputting breadcrumbs. Add this code to your theme’s functions.php file:

function wp_custom_breadcrumb() {
global $wp_query, $post;
$separator = "»";
$homelink = '<a href="'.get_bloginfo('url').'">Home</a>';
$bloglink = $homelink;

$post = $wp_query->get_queried_object();

// If this is a top level Page, it's simple to output the breadcrumb
if ( 0 == $post->post_parent )
{
$output = $homelink." ".$separator." ".get_the_title();
}
else
{
if (isset($post->ancestors)) {
if (is_array($post->ancestors))
$ancestors = array_values($post->ancestors);
else
$ancestors = array($post->ancestors);
} else {
$ancestors = array($post->post_parent);
}

// Reverse the order so it's oldest to newest
$ancestors = array_reverse($ancestors);

// Add the current Page to the ancestors list (as we need it's title too)
$ancestors[] = $post->ID;

$links = array();
foreach ( $ancestors as $ancestor ) {
$tmp  = array();
$tmp['title']     = strip_tags( get_the_title( $ancestor ) );
$tmp['url']     = get_permalink($ancestor);
$tmp['cur'] = false;
if ($ancestor == $post->ID) {
$tmp['cur'] = true;
}
$links[] = $tmp;
}

$output = $homelink;
foreach ( $links as $link ) {
$output .= ' '.$separator.' ';
if (!$link['cur']) {
$output .= '<a href="'.$link['url'].'">'.$link['title'].'</a>';
} else {
$output .= $link['title'];
}
}
}
return $output;
}

Step2: Showing WordPress Breadcrumbs On Your WordPress Site

We are not going to utilize the custom breadcrumbs function we created above and use it to show breadcrumbs on the site.

Add the following snippet of code to your theme’s template file where you want to show the breadcrumbs. You can add this code to your “single.php” file of your theme:

<?php
if(function_exists('wp_custom_breadcrumb')){
echo wp_custom_breadcrumb();
}
?>

That should do it. You should have nice breadcrumbs on your site now.


Viewing all articles
Browse latest Browse all 39

Trending Articles