WordPress.org

Ready to get started?Download WordPress

Forums

Add class to links generated with wp_page_menu (4 posts)

  1. Drew Baker
    Member
    Posted 3 years ago #

    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!

  2. vtxyzzy
    Member
    Posted 3 years ago #

    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;
  3. Drew Baker
    Member
    Posted 3 years ago #

    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'
    
    		});
    	});
  4. vtxyzzy
    Member
    Posted 3 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic