Welcome to my day 6 of ruthlessly learning custom WordPress!
1) Dynamic way:-
Check the code below in functions.php file:-
function university_features() {
//add all sorts of default wp functions
add_theme_support('title-tag');
//to add dynamic menu option in wordpress. First argument is variable. Second argument gives the name on menu settings
register_nav_menu('headerMenuLocation', 'Header Menu Location');
register_nav_menu('footerMenuLocationOne', 'Footer Menu Location One');
register_nav_menu('footerMenuLocationTwo', 'Footer Menu Location Two');
}
add_action('after_setup_theme', 'university_features');
As you can see above that we are using register_nav_menu() which takes 2 arguments.
1st argument - Variable name you want to give for the menu
2nd argument - Name of the menu type to show
As you can see below on the nav menu settings on the WordPress dashboard, the menu names of register_nav_menu() are showing.
To use the menu on the header we then use wp_nav_menu(); function which takes array as an argument to add the menu variable name which you set in function.php file.
Something like this:-
<nav class="main-navigation">
<?php
wp_nav_menu(array(
'theme_location' => 'headerMenuLocation' //menu variable
));
?>
</nav>
Now as we add a menu in the header like this:-
We see something like this on the nav bar:-
The same we can do on the footer too.
Now, you may want to use this only if you are trying to sell the theme and want users to add a nav menu on their own. Else, keep it static.
2) Static way to highlight menu name:-
Now, in a dynamic way the menu items are automatically highlighted by WordPress function when you are on the current page like this:-
But if you want to use a static way to highlight, use the following code to highlight menu in manual way:-
<li <?php if(is_page('about-us') or wp_get_post_parent_id(0) == 16) echo 'class="current-menu-item"' ?>>
<a href="<?php echo site_url('/about-us') ?>">About Us</a></li>
Here, is_page('about-us') function is checking if the current page is About Us or wp_get_post_parent_id(0) == 16 is checking if the current page is a child page of About Us, since About Us has page ID=16.
You can check the page ID when you edit any page on WordPress like this:-
That's it for today. See you on day 7!