Random get_template_part in WordPress

I’m looking for a way to show four template parts in a random order. They’re arranged in a 2×2 grid and I need the order to be different every time the page loads. Here’s the code:

<!-- Feature 1 -->
      <div class="grid_half">
        <?php get_template_part( 'features/feat','1' ); //Get Features Section 1 ?>
    </div><!-- /.grid_half -->
<!-- Feature 2 -->
      <div class="grid_half_last"> 
        <?php get_template_part( 'features/feat','2' ); //Get Features Section 2 ?>
     </div><!-- /.grid_half_last -->
      <div class="clear"></div>
<!-- Feature 3 -->
      <div class="grid_half"> 
        <?php get_template_part( 'features/feat','3' ); //Get Features Section 3 ?>
      </div><!-- /.grid_half -->
<!-- Feature 4 -->
      <div class="grid_half_last">
        <?php get_template_part( 'features/feat','4' ); //Get Features Section 4 ?>
      </div><!-- /.grid_half_last -->
      <div class="clear"></div>

Related posts

Leave a Reply

2 comments

  1. $order = array(1, 2, 3, 4);
    shuffle($order);
    

    Then:

    get_template_part( 'features/feat', array_shift($order) );
    

    To ensure you don’t get the same order within 4 consecutive page requests, you’ll have to keep track of this array, perhaps trough sessions or client cookies.

  2. This seems to be working for me:

        <?php $features = array('1', '2', '3', '4'); 
            shuffle($features); ?>
    <!-- Feature 1 -->
          <div class="grid_half">
            <?php get_template_part( 'features/feat', $features[0] ); //Get Features Section 1 ?>
        </div><!-- /.grid_half -->
    <!-- Feature 2 -->
          <div class="grid_half_last"> 
            <?php get_template_part( 'features/feat', $features[1] ); //Get Features Section 2 ?>
         </div><!-- /.grid_half_last -->
          <div class="clear"></div>
          <br />
          <br />
          <!-- Feature -->
          <div class="grid_half"> 
            <?php get_template_part( 'features/feat', $features[2] ); //Get Features Section 3 ?>
          </div><!-- /.grid_half -->
    <!-- Feature -->
          <div class="grid_half_last">
            <?php get_template_part( 'features/feat', $features[3] ); //Get Features Section 4 ?>
          </div><!-- /.grid_half_last -->
          <div class="clear"></div>
    

    Files are named feat-1.php, feat-2.php etc. in a subfolder named features in the interests of full info.