1. 程式人生 > 其它 >wp/wordpress將引數傳遞給get_template_part()模板:動態新增帶序號的class名字

wp/wordpress將引數傳遞給get_template_part()模板:動態新增帶序號的class名字

技術標籤:pythonjavaphpjavascripthtml

今天想實現一個動態列表class的功能:從列表的第一個開始,新增class為div0,第二個列表的class名為div1,第三個列表的div的class名字為div2......效果如下圖:

這樣的需求在wp開發的時候怎麼實現呢?我們知道wp/wordpress有一個主迴圈,我們在主迴圈中呼叫一個變數,然後迴圈結束前將這個變數自動加1,就能實現,原理很簡單,看看下面怎麼實現的:

<?php
$i = 0;
 // 主迴圈
 if ( have_posts() ) : while ( have_posts() ) : the_post();
?> 
<li class="list-animation-leftIn <?php echo 'delay-'.$i; ?>"> 
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><span class="text-h1"><?php the_title(); ?></span><time><?php the_time('Y-m-d') ?></time></a>
</li> 
 <?php
$i++;
endwhile;
 ?> 

按著以上程式碼就能實現動態新增帶序號的class名字。不過七娃在開發過程也遇到另一個問題:我的主迴圈列表用了模板:get_template_part進行呼叫,即便php聲明瞭全域性變數global,模板內也不能獲取到引數,最後發現這個wp模板函式可以傳參:

//設定引數
set_query_var('引數名', 值);

//獲取引數
get_query_var('引數名');

這樣大家就屬性了,在主迴圈內先設定引數$i,然後模板從新獲取一下這個引數就可以了:

1.主迴圈程式碼:

<?php
$i = 0;//生命引數
 // 主迴圈
if ( have_posts() ) : while ( have_posts() ) : the_post();
set_query_var('i', $i);//設定引數
get_template_part( 'tool/loop' ); //呼叫模板
$i++;//引數自動加+
endwhile; ?> 

2.模板內程式碼:

<?php  
$i = get_query_var('i');//獲取引數
<?php } ?>
<li class="list-animation-leftIn <?php echo 'delay-'.$i; ?>"> 
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><span class="text-h1"><?php the_title(); ?></span><time><?php the_time('Y-m-d') ?></time></a>
</li>  
版權宣告:原創作品,允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本宣告。否則將追究法律責任。 轉載請註明來源: wp/wordpress將引數傳遞給get_template_part()模板:動態新增帶序號的class名字 - Qui-Note