Add Custom Breadcrumbs Navigation To Your WordPress Website An Optimized Solutions

Add Custom Breadcrumbs Navigation To Your WordPress Website Without Plugin

Breadcrumbs navigation is an essential part of any website’s navigation, as they provide a clear path for users to follow from the homepage to their current location. In this blog post, we will discuss how to create WordPress custom breadcrumbs without plugin using the best WordPress coding standards and latest PHP 8.0 syntax. We will delve into the code and explain each variable, function, and functionality to help you understand the process better. So, let’s dive in!

Code To Add WordPress Custom Breadcrumbs Without Plugin

Just copy and paste the following code into your theme’s functions.php file.

// Add WordPress Custom Breadcrumbs Without Plugin

// Define the custom_breadcrumbs() function

function custom_breadcrumbs() {

    // Access the global $post variable, which contains information about the current post or page being displayed

    global $post;



    // Create an ordered list with the class "breadcrumb" and include schema markup for a breadcrumb list

    echo '<ol class="breadcrumb" itemscope itemtype="https://schema.org/BreadcrumbList">';



    // Check if the current page is not the homepage, as breadcrumbs should not be displayed on the homepage

    if (!is_home()) {

        // Create a list item with schema markup for the homepage link

        echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">';

        echo '<a itemprop="item" href="' . esc_url(home_url('/')) . '"><span itemprop="name">' . __('Home', 'textdomain') . '</span></a>';

        echo '<meta itemprop="position" content="1" />';

        echo '</li>';



        // Check if the current page is either a category archive or a single post

        if (is_category() || is_single()) {

            // Retrieve the category information of the current post

            $category = get_the_category();

            $category_id = $category[0]->cat_ID;



            // Fetch the parent categories of a given category and return them as a string, separated by a specified delimiter

            $parents = get_category_parents($category_id, true, '|', false);



            // Check if the returned value from get_category_parents() is a WordPress error

            if (!is_wp_error($parents)) {

                // Explode the parent categories string into an array

                $parent_array = explode('|', $parents);

                $count_parents = count($parent_array);

                $i = 2;



                // Iterate through the parent categories and display them with schema markup

                foreach ($parent_array as $parent) {

                    if ($parent) {

                        echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">';

                        echo $parent;

                        echo '<meta itemprop="position" content="' . $i . '" />';

                        echo '</li>';

                        $i++;

                    }

                }

            }



            // If the current page is a single post, display the post title with schema markup

            if (is_single()) {

                echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">';

                echo '<span itemprop="name">' . get_the_title() . '</span>';

                echo '<meta itemprop="position" content="' . $i . '" />';

                echo '</li>';

            }

        // If the current page is a static page, display the page title with schema markup

        } elseif (is_page()) {

            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">';

            echo '<span itemprop="name">' . get_the_title() . '</span>';

            echo '<meta itemprop="position" content="2" />';

            echo '</li>';

        }

    }

    // Close the ordered list

    echo '</ol>';

}

A Boilerplate Template of Your Single Post and Single Page Templates To Add WordPress Custom Breadcrumbs Without Plugin

The following code shows you where you need to place the custom_breadcrumbs() function.

<?php

// Load the header template

get_header();

?>



<main id="main" class="site-main">

    <?php

    // Start the Loop

    while (have_posts()) :

        // Set up the current post's data

        the_post();

        ?>



        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

            <header class="entry-header">

                <?php

                // Call the custom_breadcrumbs() function to display breadcrumbs

                custom_breadcrumbs();

                ?>

                <h1 class="entry-title">

                    <?php

                    // Display the current post's title

                    the_title();

                    ?>

                </h1>

            </header>



            <div class="entry-content">

                <?php

                // Display the content of the current post

                the_content();



                // Display pagination for multi-page posts

                wp_link_pages(array(

                    'before' => '<div class="page-links">' . __('Pages:', 'textdomain'),

                    'after'  => '</div>',

                ));

                ?>

            </div>



            <footer class="entry-footer">

                <?php

                // Display an edit link if the current user has the capability to edit the post

                edit_post_link(

                    sprintf(

                        // Allow only specific HTML elements in the 'Edit' link

                        wp_kses(

                            __('Edit <span class="screen-reader-text">%s</span>', 'textdomain'),

                            array(

                                'span' => array(

                                    'class' => array(),

                                ),

                            )

                        ),

                        // Insert the current post's title as a screen-reader-text

                        get_the_title()

                    ),

                    // Add a wrapper for the 'Edit' link

                    '<span class="edit-link">',

                    '</span>'

                );

                ?>

            </footer>

        </article>



        <?php

        // Check if comments are open or if there are comments, and load the comments template

        if (comments_open() || get_comments_number()) {

            comments_template();

        }

        ?>



    <?php

    // End the Loop

    endwhile;

    ?>

</main>



<?php

// Load the footer template

get_footer();

Understanding the custom_breadcrumbs() Function That Generated WordPress Breadcrumbs Programmatically

The custom_breadcrumbs() function is a PHP function that generates breadcrumb navigation for your WordPress website. This function can be easily integrated into your theme's functions.php file and can be called within your theme templates to display breadcrumbs with proper schema markup.

Breaking Down the custom_breadcrumbs() Code

Let's examine the custom_breadcrumbs() function line by line to understand its variables, functions, and overall functionality.

  • global $post;: The global keyword is used to access the global $post variable. The $post variable is an instance of the WP_Post class and contains information about the current post or page being displayed. By declaring the variable as global, we can access and use its data within the custom_breadcrumbs() function.
  • echo '<ol class="breadcrumb" itemscope itemtype="https://schema.org/BreadcrumbList">';: This line of code creates an ordered list (ol) element with the class "breadcrumb". The itemscope and itemtype attributes define the element as a "BreadcrumbList" according to the schema.org vocabulary. Schema markup helps search engines understand the content and structure of the breadcrumbs.
  • if (!is_home()): The is_home() function checks if the current page is the homepage. The ! operator negates the result, meaning that the following code block will only execute if the current page is NOT the homepage. This ensures that breadcrumbs are not displayed on the homepage, as they are not necessary there.
  • echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">';: This line creates a list item (li) element with itemprop="itemListElement", which indicates that it's part of the BreadcrumbList. The itemscope and itemtype attributes define the element as a "ListItem" according to the schema.org vocabulary.
  • is_category() || is_single(): These functions check if the current page is a category archive or a single post, respectively. The || operator is a logical OR, meaning that if either condition is true, the following code block will execute. This ensures that breadcrumbs are displayed on both category archive pages and single post pages.
  • get_the_category(): This function retrieves an array of category objects for the current post. Since a post can belong to multiple categories, it returns an array even if there's only one category.
  • $category_id = $category[0]->cat_ID;: This line gets the ID of the first category in the array. It assumes that the first category is the most relevant one for generating the breadcrumb trail.
  • get_category_parents(): This function retrieves all the parent categories of a given category ID, formatted as a string. The parameters include the category ID, whether to include links in the output (true), a delimiter to separate the categories ('|'), and whether to display errors (false).
  • is_wp_error(): This function checks if the result of get_category_parents() is a WordPress error. If it's not an error, the following code block will execute to display the parent categories in the breadcrumb trail.
  • is_single(): This function checks if the current page is a single post. If true, the following code block will execute, adding the post title to the breadcrumb trail.
  • is_page(): This function checks if the current page is a static page. If true, the following code block will execute, adding the page title to the breadcrumb trail.

Implementing the custom_breadcrumbs() Function in the single-post.php Template

In this section, we will provide a more detailed explanation of how to implement the custom_breadcrumbs() function in the single-post.php template. The single-post.php file is the template file responsible for displaying individual blog posts in WordPress. By adding the custom_breadcrumbs() function to this template, you can ensure that breadcrumb navigation is displayed on every single blog post page.

Here are the steps to implement the custom_breadcrumbs() function in the single-post.php template:

1. Locate or create the single-post.php file:

In your WordPress theme folder, locate the single-post.php file. If it does not exist, create a new file with that name.

2. Add the custom_breadcrumbs() function within the entry-header section:

Open the single-post.php file in a code editor, and locate the entry-header section of the code. This section typically includes the post title and other metadata. To display breadcrumbs above the post title, add the custom_breadcrumbs() function call just before the title, like this:

<header class="entry-header">

    <?php custom_breadcrumbs(); ?>

    <h1 class="entry-title"><?php the_title(); ?></h1>

</header>

In this code snippet, we start with an opening <header> tag that contains the class "entry-header". Inside the <header> tag, we call the custom_breadcrumbs() function using <?php custom_breadcrumbs(); ?>. This line of code will output the breadcrumb navigation generated by the custom_breadcrumbs() function.

Following the custom_breadcrumbs() function call, we have an <h1> tag with the class "entry-title" that displays the current post's title using <?php the_title(); ?>.

3. Save and test the single-post.php file:

After adding the custom_breadcrumbs() function call to the single-post.php template, save the file, and upload it to your theme folder if you are working locally. Visit a single blog post page on your WordPress site and verify that the breadcrumb navigation is displayed correctly above the post title.

Remember that you must have added the custom_breadcrumbs() function to your functions.php file for it to work in the single-post.php template. If you haven't done so yet, follow the instructions provided earlier in this guide to add the custom_breadcrumbs() function to your functions.php file.

By following these steps, you can successfully implement the custom_breadcrumbs() function in your single-post.php template, adding breadcrumb navigation to every individual blog post page on your WordPress website.

Testing and tweaking your custom breadcrumbs

After implementing the custom_breadcrumbs() function in your theme, be sure to test it on various pages and post types to ensure it works as expected. If necessary, tweak the function to accommodate custom post types or additional taxonomy structures.

Conclusion

In this blog post, we have discussed how to create custom breadcrumbs in WordPress using PHP 8.0. We have examined the custom_breadcrumbs() function and its various components and explained how to implement it in your theme's single-post.php template. By following this guide, you can create a custom breadcrumb navigation system that is both user-friendly and search-engine-optimized. Happy coding!

Buffer Pinterest