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="/">
C++ History and advantages
</a>
</li>
and the css I want to apply is
.current_page_item{
background-color:#4ba668;
color: white;
display:block;
}
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/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;
}
Share
Improve this question
asked Jan 27, 2021 at 7:55
KanjooKanjoo
11 bronze badge
2
|
1 Answer
Reset to default 0WordPress 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.
current-menu-item
class - is this not sufficient for your needs? – bosco Commented Jan 28, 2021 at 15:44