Wordpress Adding Class To Your Menu List

/ Published in: PHP
Save to your folder(s)

Copy this code and paste it in your HTML
  1. One of the problems of using wp_page_menu is that the HTML is all wrapped in the function. You can’t get at it. Which is a pain if you want to use the function but also want to add special classes for implementing javascript drop-down menus or do some trickier CSS without giving yourself a headache. Luckily, you can filter it. Here’s how to filter wp_page_menu and add a unique class to the first instance of the ul tag, using PHP’s preg_replace to find the first ul tag and adding in id and class attributes.
  2. // Add ID and CLASS attributes to the first <ul> occurence in wp_page_menu
  3. function add_menuclass($ulclass) {
  4. return preg_replace('/<ul>/', '<ul id="nav" class="something-classy">', $ulclass, 1);
  5. }
  6. add_filter('wp_page_menu','add_menuclass');

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.