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: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’ve ever created a custom navigation menu in WordPress, you may have noticed that there’s no easy way to add a link back to your homepage. This can be frustrating if you want users to be able to quickly return to the main page of your site. Fortunately, there is a simple solution to this problem – adding a home link to your wp_nav_menu. In this article, we’ll show you how to do just that, so let’s dive in!

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

The code snippet above adds a Home link to the WordPress navigation menu, using the wp_nav_menu_items filter hook.

The first part of the code defines a new function – wpturbo_add_home_link_to_nav_menu(). This function takes two arguments – $items and $args. The $items parameter contains the HTML markup for the navigation menu items, and the $args parameter is an object that holds additional parameters related to the current menu.

The function then checks if the menu location is ‘primary’, which is the name of the menu location registered in the theme. The reason for this check is to ensure that the Home link is only added to the primary menu and not to other menus.

If the menu location is ‘primary’, the function creates a new HTML list item (<li>) with a class of ‘home’. Inside the list item, an anchor (<a>) tag is created that links to the site’s homepage using the home_url() function. The display text for the anchor text is set to ‘Home’ using the __() function, which makes the Home text translatable.

Next, the $items variable is assigned to the string concatenation of $home_link (our new list item) and $items (the original navigation menu items), which ensures that our new Home link is added to the beginning of the list.

Finally, this modified $items string is returned, which WordPress will use to render the navigation menu on the front-end.

Lastly, the function is hooked to the wp_nav_menu_items filter hook using add_filter(). This ensures that WordPress calls our function whenever it generates the list of navigation menu items.

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