【问题标题】:Random get_template_part in WordpressWordpress 中的随机 get_template_part
【发布时间】:2013-02-17 00:00:44
【问题描述】:

我正在寻找一种以随机顺序显示四个模板部分的方法。它们排列在 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>

【问题讨论】:

    标签: php wordpress templates random


    【解决方案1】:
    $order = array(1, 2, 3, 4);
    shuffle($order);
    

    然后:

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

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

    【讨论】:

    • 他还可以将当前模板编号存储为会话变量,并在下一页加载时从数组中删除该编号
    • &lt;?php $features = array('1', '2', '3', '4'); shuffle($features); ?&gt;&lt;?php get_template_part( 'features/feat', $features[0] ); //Get Features Section 1 ?&gt; 我一发布就知道了。谢谢你们的帮助
    【解决方案2】:

    这似乎对我有用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多