我正在寻找一种以随机顺序显示四个模板部件的方法。它们被安排在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>
答案 0 :(得分:2)
$order = array(1, 2, 3, 4);
shuffle($order);
然后:
get_template_part( 'features/feat', array_shift($order) );
为了确保您在连续4次页面请求中没有获得相同的订单,您必须跟踪此数组,可能是通过会话或客户端cookie。
答案 1 :(得分: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等,以获取完整信息。