0

I'm trying to have menu items show an underline under the related nav item when when the user on a specific page (image attached).

In the static site version of the site I'm doing I had a php variable at the top of each page such as:

<?php $page = "home"; ?>

Then in the menu item in the header, I did the following which added a 'page_active' class when someone is on the relevant page, which I could then style accordingly with CSS:

<li><a href="./" class="<?php if ($page=="home"){echo 'page_active';}?>">HOME</a></li>

Now I've moved it over to a custom WordPress theme this isn't working. I'm placing the variable above the get_header() function on each page:

<?php $page = "home";?>
<?php get_header();?>

Because this site has a couple of large submenus in the nav, using the is_page() function to detect the page url isn't going to work. For instance I have 11 submenu items under one of the main menu items.

** EDIT ** I've added two further pictures showing that when you click on one of the submenu items and got to a 'Practice Area' page, the parent 'Practice Area' menu item is underlined. This is from a static site version where I used the php code above.

enter image description here

enter image description here

enter image description here

  • "large submenus" - are they custom links (e.g. google.com, facebook.com, etc.) or standard links like WordPress Pages, Terms/Categories, etc.? If so, then conditional tags like is_page() and is_category() should work fine. – Sally CJ Oct 12 at 22:27
  • @SallyCJ Hi they are WordPress pages, but I don't understand how using is_page() will work. I understand how to get it to work for straightforward menu items, but if I have 11 submenu items, and I want it so when someone visits one of those pages it shows the Parent Menu Item as underlined. E.g. in the new photos I've added, I want it so when if someone chooses a 'Practice Area' page when they land on this page the 'practice area' parent menu item is underlined. The examples given are on the static site & I just used the php code in the question. Thanks – The Chewy Oct 13 at 1:21
  • check the difference in <body> class of the pages, you can them as selectors for CSS targeting. :-) – majick Oct 13 at 5:26
  • @TheChewy How is the menu created? Have you hard-coded it? Are using wp_nav_menu()? Do you use some plugin? Have you written a custom walker for your menu? – Antti Koskinen Oct 13 at 7:14
  • 1
    @TheChewy With wp_nav_menu() you should get a whole bunch of default css classes, which you can use to detect which page is currently displayed, developer.wordpress.org/reference/functions/wp_nav_menu/… – Antti Koskinen Oct 13 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.