Show 2 random li’s on from ul – PHP

Hoping someone can help.

I’m building a wordpress site and as part of the design, I’ve got some ‘feature panels’ that I’d like to show.

Read More

There’s a total of 4 li’s in the list – but I’d only like to show 2 random ones on every page.

I can do it via CSS by showing / hiding each li based on the page’s class – however I’m wondering whether there’s a more elegant way of doing the same via PHP?

My HTML is here… I have no idea where to start with the PHP and it seems that I’m Googling the wrong keywords…

    <ul id="featurePanels">
  <li id="newBoatsPanel">
    <h3><a href="#">New Boats<br />
      <span>Text</span></a></h3>
  </li>
  <li id="brokeragePanel">
    <h3><a href="#">Brokerage<br />
      <span>Text</span></a></h3>
  </li>
  <li id="newsPanel">
    <h3><a href="#">News<br />
      <span>Text</span></a></h3>
  </li>
  <li id="partsPanel">
    <h3><a href="#">Parts<br />
      <span>Need text here</span></a></h3>
  </li>
</ul>

Any pointers would be greatly appreciated.

Thank you.

Related posts

Leave a Reply

2 comments

  1. <?php
    
    $listItems = array(
     '<li id="newBoatsPanel">your text here</li>',
     '<li id="brokeragePanel">more text here</li>',
     '<li id="newsPanel">text text text</li>',
     '<li id="partsPanel">Need text here</li>'
    );
    
    shuffle($listItems); // shuffles (randomizes the order of the elements)
    
    // print the list
    echo '<ul id="featurePanels">' . $listItems[0] . $listItems[1] . '</ul>';
    
    ?>
    
  2. You can use
    preg_match_all('/<li.*?>.*?</li>/i',$html_string,$li_list)

    in $li_list you will have an array of li’s and now you can shuffle, random, splice, slice or whatever…

    and at the end use implode to get the HTML.