Support » Fixing WordPress » Add class to links generated with wp_page_menu

  • Hey Guys,
    I’m trying to turn the output of wp_page_menu into an accordion menu using the default jQuery implementation.

    Is there a way to get wp_page_menu to give only the top level a (or li) tag’s their own class? Like this:

    <ul>
          <li><a class="top-level">"Link 1</a></li>
          <li><a class="top-level">"Link 1</a></li>
          <li><a class="top-level">"Link 1</a>
                <ul>
                      <li><a>"Link 1</a></li>
                </ul>
          </li>
    </ul>

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • I think this will do what you want:

    $list = wp_page_menu(array('echo' => 0,));
    $parts = preg_split('/(<ul.*?>|<li.*?<\/a>|<\/li>|<\/ul>)/',$list,null,PREG_SPLIT_DELIM_CAPTURE);
    $newlist = '';
    foreach ($parts as $part) {
      if (preg_match('/^<ul/',$part)) ++$depth;
      if (preg_match('/^<\/ul/',$part)) --$depth;
      if (preg_match('/^<li/',$part) && $depth == 1) {
        if (strpos($part,'class="') !== false) {
          $part = preg_replace('/class="/','class="top-level ',$part);
        } else {
          $part = preg_replace('/<li/','<li class="top-level" ',$part);
        }
      }
      $newlist .= $part;
    }
    echo $newlist;

    Thanks so much vtxyzzy! Did you write this yourself or find it someplace. Worked perfectly, other than it gave the li elemnts the class, not the first a of each li. It doesn’t matter, I got it working using that sturcture. If anyone is curious,I used this jQuery code to do it:

    jQuery(document).ready(function($) {
    		$( '.menu ul' ).accordion({
    			autoHeight: false,
    			header: 'li.top-level > a',
    			collapsible: true,
    			active: 'li.top-level.current_page_ancestor a'
    
    		});
    	});

    Glad you got it working. The code is my own. Now, please use the dropdown at top right to mark this topic ‘Resolved’.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add class to links generated with wp_page_menu’ is closed to new replies.