我正在嘗試通過創建自己的 Wordpress 主題來學習一些 PHP。我似乎對一個問題感到茫然,而谷歌并沒有多大幫助!我正在嘗試為我的 foreach 回圈中的每個專案添加一個唯一的類名。我已經讓它與帖子 ID 一起使用,但這不是一個可行的解決方案。
問題:
我正在用 3 個最新帖子創建 3 個框。所有帖子都需要一個不同的類名,以便它們可以放置在 CSS 網格中(很難解釋設計,但這基本上是我需要的)。我的想法是,每個帖子都可以獲得一個類名或 ID,例如第一個為“item1”,下一個為“item2”等。因此在每個回圈中,它都會為類名添加 1。
我該怎么做呢?基于我對 React 的了解,我想知道 PHP 中是否有類似的鍵功能?
這是我的參考代碼:
<section class="classmain">
<?php
$args = array( 'numberposts' => 3, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<div class="testrun">
<img src="<?php the_post_thumbnail_url('blog-small');?>" alt="<?php the_title();?>" style="margin-right: 20px">
<br />
<!-- <?php the_date(); ?>
<br />
<?php the_title(); ?>
<br />
<?php the_excerpt(); ?>
<br /> -->
</div>
<?php endforeach; ?>
</section>
uj5u.com熱心網友回復:
將索引添加到您的 foreach 回圈中:
foreach ($postslist as $index => $post) :
并使用它附加到類名:
<div class="testrun<?= $index ?>">
只要陣列是索引陣列,你會得到testrun0,testrun1,testrun2等。
如果您想以1代替開頭0,只需將其更改為:
<div class="testrun<?= $index 1 ?>">
uj5u.com熱心網友回復:
你可以嘗試這樣的事情。
<?php
$i = 1;
foreach ($postslist as $post) : setup_postdata($post); ?>
<div class="testrun <?php echo "item".$i; ?>">
<img src="<?php the_post_thumbnail_url('blog-small');?>" alt="<?php the_title();?>" style="margin-right: 20px">
<br />
<!-- <?php the_date(); ?>
<br />
<?php the_title(); ?>
<br />
<?php the_excerpt(); ?>
<br /> -->
</div>
<?php $i ; endforeach; ?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419696.html
標籤:
