0

I have a custom vertical menu based on posts of a specific category. I want to match the slug of the menu item with the slug of the current post to apply css. Specifically, I want to change the background of the selected menu item. Selected menu item means, when the user clicks the menu and page loads, the background of that menu item should be changed indicating the user is at this menu item/post. What I think, if the menu item consists of posts, then the slug of the posts and slug of the menu item should be same. In the html, each li tag has the menu item ID. The code I am is like this

<?php 
    global $post;
    $post_slug = $post->post_name;
//get menu item id corresponding to the post/menu item slug
//apply css
?>

One of the li element of hmtl is

<li id="menu-item-227" class="menu-item menu-item-type-post_type menu-item-object-post menu-item-227">
        <a href="https://www.tutorialsart.com/cpp-history-and-advantages/">
          C++ History and advantages
        </a>
</li>

and the css I want to apply is

.current_page_item{
   background-color:#4ba668;
  color: white;
  display:block;
}
2
  • The menu item corresponding to the post you are currently viewing should already receive a current-menu-item class - is this not sufficient for your needs?
    – bosco
    Jan 28, 2021 at 15:44
  • @bosco you are right, I did not know. Thanks for the comment.
    – Kanjoo
    Mar 2, 2021 at 13:28

1 Answer 1

0

WordPress already has current-menu-item class. Following CSS can be applied.

.current-menu-item{
   background-color:#4ba668;
  color: white;
  display:block;
}

Thanks to bosco for his comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.