Sort order on snippet menu

So I have a strange issue where im using a snippet to list pages. Im passing a list of ID numbers through on the snippet, and I want the menu items to come out in that specific order. However, they are coming out in alpha order. How can i get it to respect the order i set in the snippet?

Here is my snippet call:

<?php snippet('navs/nav-pagelist', array('pagelist' => ['29', '58', '65'])) ?>

And here is the contents of that snippet:

<?php $pagelister = $pagelist  ?>
<ul>
  <?php foreach ($pages->visible()->filterBy('autoid', 'in', $pagelister) as $sitenav): ?>
  <?php if ($sitenav->featureinnav()->bool()):
    $string = $sitenav->menutitle()->html();
    $pattern = '/\b('.'for'.')\b/i';
  ?>

  <li id="<?= $sitenav->uid() ?>-menu"><a <?php e($sitenav->isOpen(), ' class="active"') ?> href="<?= $sitenav->url() ?>"><?= preg_replace($pattern, '<sup>$0</sup>', $string) ?></a></li>

  <?php endif ?>
  <?php endforeach ?>
</ul>

What am i missing?

Well, you are not assigning any sort order to your pages, you just filter by whether or not they are in the array or not. Since you want them in ascending order, you have to sort them first by autoid and then filter.

On a side note, why do you assign a variable to another variable instead of using the pagelist variable within your snippet? Seems unnecessary.

Those numbers happen to run in ascending order in this case, but they might not. Basically i want them to come out in the exact order set in the array. No sorting at all. How can I do that?

Yes your right, i saw that myself after i posted. Wrote it in a hurry a while back, Tidied up now.

Ok, if we can’t go down the sorting route, then I’d first filter the pages like you did and then run through the array of ids and pick the matching page.

Im not sure I follow that last bit… sounds as if it would be simpler to hard code the links but I would rather have a dynamic way. This is one of those sites that has the main menu cut in half by the companies logo, so im using the same snippet on either side, but feeding it different IDs

Like this:

$relevantPages = $pages->visible()->filterBy('autoid', 'in', $pagelist);
foreach($pagelist as $id) {
  if($p = $relevantPages->findBy('autoid', $id))
    echo $p->title();
  }
}
1 Like

Smashing! Thank you… this did it…

<?php $relevantPages = $pages->visible()->filterBy('autoid', 'in', $pagelist); ?>
<ul>
  <?php foreach($pagelist as $id): ?>
    <?php if($p = $relevantPages->findBy('autoid', $id)):?>
      <?php if ($p->featureinnav()->bool()):
        $string = $p->menutitle()->html();
        $pattern = '/\b('.'for'.')\b/i';
      ?>
      <li id="<?= $p->uid() ?>-menu"><a <?php e($p->isOpen(), ' class="active"') ?> href="<?= $p->url() ?>"><?= preg_replace($pattern, '<sup>$0</sup>', $string) ?></a></li>
      <?php endif ?>
    <?php endif ?>
  <?php endforeach ?>
</ul>