Menü schliessen
Created: November 29th 2023
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to generate breadcrumbs

Tags:  guide,  HTML,  PHP,  seo,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Breadcrumbs are a hierarchical navigation aid that displays the path a user has taken to reach the current page within a website. Typically appearing horizontally at the top of a webpage, breadcrumbs provide users with a trail of links, allowing them to navigate back to parent pages effortlessly.


Generating Breadcrumbs

To generate breadcrumbs in WordPress, we'll utilize PHP code to dynamically construct the breadcrumb trail based on the current page's hierarchy. Below is the PHP code snippet that you can integrate into your WordPress theme's template files:

<?php

function get_parent($post) {
    if (!isset($post->post_parent) || !$post->post_parent) {
        return null;
    }

    return get_post($post->post_parent);
}

$current_post = get_post();

if (!is_search() && !empty($current_post)) {
    $hierarchy = [];

    $hierarchy[] = $current_post;

    while ($current_post = get_parent($current_post)) {
        $hierarchy[] = $current_post;
    }

    if (!empty($hierarchy) && count($hierarchy) > 1) {
        $hierarchy = array_reverse($hierarchy);

        ?>

        <ol id="breadcrumbs" itemscope itemtype="https://schema.org/BreadcrumbList">
            <?php

            $counter = 1;

            foreach ($hierarchy as $breadcrumb_item) {
                ?>

                <li class="breadcrumb-item" itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
                    <a itemprop="item" class="breadcrumb-link" href="<?= esc_attr(wp_make_link_relative(get_permalink($breadcrumb_item->ID))) ?>">                    
                        <span itemprop="name">
                            <?= esc_html($breadcrumb_item->post_title) ?>
                        </span>
                    </a>

                    <meta itemprop="position" content="<?= esc_attr($counter) ?>" />
                </li>

                <?php

                $counter++;
            }

            ?>
        </ol>

        <?php
    }
}

?>

How it works

  • get_parent() Function: This function retrieves the parent post of the current post/page.
  • Hierarchy Construction: The code constructs an array $hierarchy containing the current post and its parent posts recursively.
  • Breadcrumb Markup: Inside the loop, each post in the $hierarchy array is formatted as a breadcrumb item with schema.org markup for enhanced SEO.