WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» Add a Custom Class in WordPress Menu Item using Conditional Statements

Add a Custom Class in WordPress Menu Item using Conditional Statements

Last updated on June 22nd, 2012 by Editorial Staff
53 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
Add a Custom Class in WordPress Menu Item using Conditional Statements

In most cases when styling WordPress navigation menus, you can simply add CSS classes from the WordPress admin panel. Recently while working on a project, we found ourselves in a troublesome situation. We wanted to add a custom class to a specific menu item only on single post pages. After looking around for a while, we could not find any solution. Our last resort was to ask on twitter. Otto (@Otto42) replied by saying it is possible by using filters, but there are no documentation for the filter.

After looking in the core for a while, we figured out the solution. What you need to do is paste the following code in your functions.php file:

//Filtering a Class in Navigation Menu Item
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
     if(is_single() && $item->title == 'Blog'){
             $classes[] = 'current-menu-item';
     }
     return $classes;
}

The code above is simply checking if it is a single post page, and the menu item title is Blog. If the criteria is matched, then it is adding a class “Current-menu-item”. We needed to add a custom class in order to make it work with this design that we are working on.

If you can’t tell already, basically what we wanted to do was keep the blog item highlighted in the menu when the user was on a single post. This allowed them to see that the single posts are part of the blog. This normally doesn’t make sense, but in the design that we are working on, it did make sense.

If you were desperate looking for this code, we hope that this article helped. You can check for other $item variables also. Some examples are: $item->ID, $item->title, $item->xfn

Quick Edit: After posting this article on twitter, one of our users @dbrabyn pointed out that we could’ve easily accomplished this with CSS Body classes. For example:

.single #navigation .leftmenublog div{display: inline-block !important;}

Basically what we did was added an additional div to display an arrow icon to our menu. This arrow would only be shown if the class was either hovered over, or selected. Otherwise it was set to display: none; By using the body class, we just made the div element display only for the specific menu class.

53 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

15 Comments

Leave a Reply
  1. Christian says:
    Sep 21, 2017 at 4:36 am

    Thanks,

    The filter helped me highlighting the current “Blog” menu item on the static blog page and on the single post page.

    Reply
  2. Ali Babaeian says:
    Oct 2, 2016 at 3:45 am

    hi, I’ve used wp nav Custom Class for menu items:
    but the icon is not contains link
    how can i change the position of wp css custom class from “li” to “a href” ??

    Reply
  3. Annette Voelckner says:
    Aug 12, 2014 at 12:48 pm

    Thank you so much! After a lot of research this was exactly what I needed.

    Reply
  4. Ben says:
    Jul 2, 2014 at 10:14 am

    Any idea how this could be amended to add a class to the anchor element rather than the list element?

    Reply
  5. Matt Vaden says:
    Apr 6, 2014 at 12:35 am

    Thank you very much for this tip! I know exactly what you mean when you say that for the design you were working on you needed “Blog” to be highlighted in the menu when the user was reading a post. That is exactly what my project needed!

    If reverse (parent) selectors were available in CSS, this wouldn’t be necessary, but that’s neither here nor there, because CSS doesn’t support reverse selectors.

    Thanks again for the tip.

    Regards,
    Matt

    Reply
  6. ginjoeWP says:
    Jan 16, 2014 at 8:18 am

    Very helpful. Thank you!
    I outsourced my menu to a template part called nav-main.php
    The snippet works even when you write it just between $defaults = array(); and wp_nav_menu($defaults); Therefore, leave the functions.php untouched.

    Reply
  7. Amelie Müller says:
    Dec 26, 2013 at 4:20 am

    Wow, thanks so much. I’ve been trying to figure this for a while, you saved me!

    Reply
  8. Hugo says:
    Jul 9, 2013 at 6:55 am

    I was looking a solution for a long time, and now I’ve got it!
    THANKS A LOT

    Reply
  9. Alessandro says:
    May 7, 2013 at 5:04 am

    What’s nav_menu_css_class?

    Nothing happens in my theme…

    Reply
  10. Jayson T Cote says:
    Apr 10, 2013 at 11:54 am

    @Syed, I really appreciate all of your tuts and articles, thanks so much for this snippet. I needed to apply the same function to a client site and this saved me plenty of research time.

    Reply
    • Editorial Staff says:
      Apr 11, 2013 at 4:05 am

      Glad to help Jason
      -SB

      Reply
  11. Patricia Petro says:
    Apr 3, 2013 at 11:26 am

    Put the code in my function file . . . added ‘ && in_category ( ‘6’ ) ‘ to highlight menu item for posts in that one category . . . and it works like a dream. Thank you!

    Reply
  12. Andrea Ballerino says:
    Mar 23, 2013 at 8:31 am

    Thanks for this code, work correctly in my theme!

    Reply
  13. Mattia says:
    Dec 21, 2012 at 12:13 pm

    Doesn’t WordPress add automatically those classes (current-menu-item, current-post-category, etc.) by default?

    Reply
    • Editorial Staff says:
      Dec 24, 2012 at 7:50 am

      Yes

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WPForms Logo
WPForms
Drag & Drop WordPress Form Builder Plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
LiveChat logo
LiveChat Inc Coupon
Get a 30 day free trial and 30% OFF LiveChat, one of the best live chat service providers for WordPress users.
ConvertKit Coupon Code
ConvertKit Coupon
Get a 14-day no risk FREE trial with this powerful email marketing software.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.