Question

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;
}
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top