2013-02-17 30 views
1

我正在尋找一種以隨機順序顯示四個模板部件的方法。它們以2x2格子排列,每次頁面加載時我都需要不同的順序。下面的代碼:Wordpress中的隨機get_template_part

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

回答

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> 

文件被命名爲壯舉,1.PHP,在充分信息的利益壯舉,2.PHP等子文件夾命名的功能。

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

然後:

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

爲了確保您不會連續4個頁面請求中得到相同的順序,你必須保持這種陣列的軌道,也許槽會話或客戶端cookie。

+0

他也可以將當前模板號存儲爲會話變量,並在下一頁加載時從數組中刪除該號碼 – Booski 2013-02-17 00:06:56

+0

'<?php $ features = array('1','2','3',' 4' ); \t \t shuffle($ features); ?><?php get_template_part('features/feat',$ features [0]); // Get Features Section 1?>'不久,我發佈了它。謝謝你們的幫助 – TheTallOne 2013-02-17 00:20:14