1

我正在寻找一种以随机顺序显示四个模板部分的方法。它们排列在 2x2 网格中,每次加载页面时我都需要不同的顺序。这是代码:

<!-- 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>
4

2 回答 2

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

然后:

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

为了确保在 4 个连续的页面请求中不会获得相同的顺序,您必须跟踪这个数组,可能是通过会话或客户端 cookie。

于 2013-02-17T00:04:25.407 回答
1

这似乎对我有用:

    <?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>

为了获得完整信息,文件在名为 features 的子文件夹中命名为 feat-1.php、feat-2.php 等。

于 2013-02-17T00:22:32.170 回答