最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get post slug and match with menu item slug to change css

programmeradmin1浏览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="/">
          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
  • 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 Commented Jan 28, 2021 at 15:44
  • @bosco you are right, I did not know. Thanks for the comment. – Kanjoo Commented Mar 2, 2021 at 13:28
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论