WordPress.org

Ready to get started?Download WordPress

Forums

wp_nav_menu reverse order (3 posts)

  1. johnstonphilip
    Member
    Posted 3 years ago #

    I want to reverse the order of the items when I do a call to wo_nav_menu

    The reason being, my design has the navigation elements right-aligned so they are showing up backwards. I need to reverse them again so they show up in the right order. Is there a way to do this?

  2. vtxyzzy
    Member
    Posted 3 years ago #

    I have used the code below as a filter for wp_page_menu(). It may work for wp_nav_menu() as well:

    <?php
    function mam_reverse_page_menu ($items) {
      // Reverse the items in a page menu if the $mam_global_reverse_sw is true.
      global $mam_global_reverse_sw;
      if (!$mam_global_reverse_sw) return $items;
      $parts = preg_split('/(<ul.*?>|<li.*?<\/a>|<\/li>|<\/ul>)/',$items,null,PREG_SPLIT_DELIM_CAPTURE);
      $li_items = array();
      $in_prefix = 1;
      foreach ($parts as $part) {
        if (preg_match('/^<ul/',$part)) {
          if ($in_prefix) {
            $prefix .= $part;
            $in_prefix = 0;
          }
          ++$depth;
        }
        if (preg_match('/^<\/ul/',$part)) --$depth;
        if (preg_match('/^<li/',$part) && $depth == 1) $in_li = 1;
        if (preg_match('/^<\/li/',$part) && $depth == 1) {
          $li_item .= $part;
          $li_items[] = $li_item;
          $li_item = '';
          $in_li = 0;
        }
        if ($in_prefix) {
          $prefix .= $part;
        } elseif ($depth == 0) {
          $suffix .= $part;
        }
        if ($in_li) $li_item .= $part;
      }
      $newitems = $prefix . implode(array_reverse($li_items),'') . $suffix;
      return $newitems;
      }
    add_filter('wp_page_menu','mam_reverse_page_menu');
    ?>

    Here is the code to turn on the filter:

    $mam_global_reverse_sw = 1;
    wp_page_menu('echo=1');
    $mam_global_reverse_sw = 0;

    Turn it off right after the call to prevent reversing other menus.
    `

  3. Travis Ballard
    Member
    Posted 3 years ago #

    if you haven't figured this out yet you can use this to do it
    add_filter( 'wp_nav_menu_objects', create_function( '$menu', 'return array_reverse( $menu );' ) );

Topic Closed

This topic has been closed to new replies.

About this Topic