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:

  1. Check if it’s a page:
    • is_page() checks if the current view is a page.
  2. Global Post Object:
    • global $post; gives access to the current page’s post data.
  3. 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.
  4. Breadcrumb Creation:
    • The breadcrumb is displayed using a <nav> element with the class breadcrumb.
    • The home link (<i class="fas fa-home"></i> &nbsp;) 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.

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> &nbsp;</a>'; 
        echo '<a href="' . esc_url(home_url()) . '">' . esc_html__('Home', 'text-domain') . '</a> <a>&nbsp;<i class="fas fa-chevron-right"></i>&nbsp;</a> ';
        echo '<a href="' . esc_url($parent_url) . '">' . esc_html($parent_title) . '</a> <a>&nbsp;<i class="fas fa-chevron-right"></i>&nbsp;</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>&nbsp;<i class="fas fa-home"></i></a> &nbsp;</a>';
        echo '<a href="' . esc_url(home_url()) . '">' . esc_html__('Home', 'text-domain') . '</a> <a>&nbsp;<i class="fas fa-chevron-right"></i>&nbsp;</a> ';
        echo esc_html(get_the_title());
        echo '</nav>';
    }
}
?>                        
                        


Post Categories