Breadcrumb with conditional statement
Description


This PHP code creates a breadcrumb navigation for WordPress pages. It checks if the page has a parent page and constructs a breadcrumb trail accordingly. Here’s a breakdown of what the code does:
- Check if it’s a page:
is_page()checks if the current view is a page.
- Global Post Object:
global $post;gives access to the current page’s post data.
- Get Parent Page:
wp_get_post_parent_id($post->ID)retrieves the ID of the parent page of the current page.- If the page has a parent, it proceeds to gather the parent page’s title and URL.
- Breadcrumb Creation:
- The breadcrumb is displayed using a
<nav>element with the classbreadcrumb. - The home link (
<i class="fas fa-home"></i> ) adds a home icon using Font Awesome. - If the page has a parent, it displays the home link, then the parent page link, followed by the current page title.
- If there’s no parent, it only shows the home link followed by the current page title.
- The breadcrumb is displayed using a
PHP Source Code
<?php
if (is_page()) {
global $post;
// Get parent page
$parent_id = wp_get_post_parent_id($post->ID);
// Check if the page has a parent
if ($parent_id) {
// Get parent page title and URL
$parent_title = get_the_title($parent_id);
$parent_url = get_permalink($parent_id);
// Display the breadcrumb
echo '<nav class="breadcrumb">';
echo '<a href="' . esc_url(home_url()) . '"><a><i class="fas fa-home"></i></a> </a>';
echo '<a href="' . esc_url(home_url()) . '">' . esc_html__('Home', 'text-domain') . '</a> <a> <i class="fas fa-chevron-right"></i> </a> ';
echo '<a href="' . esc_url($parent_url) . '">' . esc_html($parent_title) . '</a> <a> <i class="fas fa-chevron-right"></i> </a> ';
echo esc_html(get_the_title());
echo '</nav>';
} else {
// If no parent, just display the current page as the breadcrumb
echo '<nav class="breadcrumb">';
echo '<a href="' . esc_url(home_url()) . '"><a> <i class="fas fa-home"></i></a> </a>';
echo '<a href="' . esc_url(home_url()) . '">' . esc_html__('Home', 'text-domain') . '</a> <a> <i class="fas fa-chevron-right"></i> </a> ';
echo esc_html(get_the_title());
echo '</nav>';
}
}
?>