How to Add a Home Link to wp_nav_menu in WordPress

Home » Snippets » How to Add a Home Link to wp_nav_menu in WordPress
0

Created with:

Visibility: 

public

Creator: Alex

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’ve ever created a custom navigation menu for your WordPress site, you may have noticed that there’s no option to add a link to your homepage. This can be frustrating, especially if you’re trying to make it easy for your visitors to navigate back to your homepage. In this article, we’ll show you how to add a home link to your WordPress navigation menu using the wp_nav_menu function. So, let’s get started!

					function wpturbo_add_home_link($items, $args) {
    if($args->theme_location == 'primary') {
        $home_link = '<li class="menu-item"><a href="' . home_url() . '">' . __('Home', 'wpturbo') . '</a></li>';
        $items = $home_link . $items;
    }
    return $items;
}
add_filter('wp_nav_menu_items', 'wpturbo_add_home_link', 10, 2);
				

In this article, I will show you how to add a home link to the WordPress navigation menu using the wp_nav_menu_items filter. This will enable you to easily provide visitors with a way to navigate back to the home page of your website.

First, we define a new function called wpturbo_add_home_link(). This function takes two parameters, $items and $args, which are passed in by the wp_nav_menu_items filter.

In this function, we check if the current menu location is the primary menu by using the theme_location property of the $args parameter. If it is, we then create a new link that points to the home page of the website using the home_url() function.

if($args->theme_location == 'primary') {
    $home_link = '<li class="menu-item"><a href="' . home_url() . '">' . __('Home', 'wpturbo') . '</a></li>';

With the new home link created, we add it to the beginning of the existing menu items by concatenating the $home_link string with $items.

 $items = $home_link . $items;

Finally, we return the new $items string and make sure to pass in the original $items and $args parameters via the wp_nav_menu_items filter.

return $items;
add_filter('wp_nav_menu_items', 'wpturbo_add_home_link', 10, 2);

By following these simple steps, you can add a home link to your WordPress navigation menu and provide visitors with an easy way to return to the home page of your website.

Register an account to save your snippets or go Pro to get more features.