...

/

Navigation Menus

Navigation Menus

Learn to add links to the navigation menu and create dynamic menus.

Navigation links

We can make the navigation links in the header and footer dynamic using the site_url() method. This method is used to retrieve the URL of the WordPress site.

site_url()

The site_url method returns the base URL of the WordPress installation that is set in the WordPress General Settings. It is used for creating links within a WordPress site or when retrieving resources such as images or scripts. The site_url function also has an optional parameter that allows us to specify a path to a specific file or page within the website. For example, site_url('/about-us/') creates a link to the About Us page on the site (as long as it is located in the root directory of the site).

We will use echo with this function so that the output is received by the browser.

Let’s start with the header. Open the header.php file and locate <div class="nav-items"> tag. The code is reproduced below:

<div class="nav-items">
<li class="current-menu-item"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Courses</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Blog</a></li>
<li><a class="sm-btn" href="#">Login</a></li>
<li><a class="sm-btn position" href="#">Sign Up</a></li>
</div>
Hardcoded navigation links

We can make the links for Home and About dynamic at this point.

In the href attribute, replace the placeholder # tag with the site_url() function, with the address of the page as argument. So for instance, for Home, we simply need to echo the root of the URL for our site.

<li><a href="<?php echo site_url() ?>">Home</a></li>
Dynamic navigation links

For the About Us page, we will pass /about-us as an argument to site_url() function. This way it will be added to the root of the website URL:

<li><a href="<?php echo site_url('/about-us');?>">About</a></li>
site_url() function
...