Could we help you? Please click the banners. We are young and desperately need the money
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.
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
}
}
?>