WP PHP - Foreach 添加不同的类名 - 它是如何工作的?
WP PHP - Foreach adding different classname - how does it work?
我正在尝试通过创建自己的 Wordpress 主题来学习一些 PHP。我似乎对一个问题一无所知,Google 帮不上什么忙!
我正在尝试为我的 foreach 循环中的每个项目添加一个唯一的类名。我已经让它与 post ID 一起工作,但这不是一个可行的解决方案。
问题:
我正在用 3 个最新的 post 创建 3 个盒子。所有 post 都需要一个不同的类名,以便它们可以放置在 CSS 网格中(很难解释设计,但这正是我所需要的)。我的想法是,每个 post 都可以获得一个类名或 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>
你可以试试这个。
<?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; ?>
将索引添加到您的 foreach 循环中:
foreach ($postslist as $index => $post) :
并使用它附加到 class 名称:
<div class="testrun<?= $index ?>">
只要数组是索引数组,你就会得到testrun0
、testrun1
、testrun2
等
如果您想以 1
开头而不是 0
,只需将其更改为:
<div class="testrun<?= $index + 1 ?>">
我正在尝试通过创建自己的 Wordpress 主题来学习一些 PHP。我似乎对一个问题一无所知,Google 帮不上什么忙! 我正在尝试为我的 foreach 循环中的每个项目添加一个唯一的类名。我已经让它与 post ID 一起工作,但这不是一个可行的解决方案。
问题:
我正在用 3 个最新的 post 创建 3 个盒子。所有 post 都需要一个不同的类名,以便它们可以放置在 CSS 网格中(很难解释设计,但这正是我所需要的)。我的想法是,每个 post 都可以获得一个类名或 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>
你可以试试这个。
<?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; ?>
将索引添加到您的 foreach 循环中:
foreach ($postslist as $index => $post) :
并使用它附加到 class 名称:
<div class="testrun<?= $index ?>">
只要数组是索引数组,你就会得到testrun0
、testrun1
、testrun2
等
如果您想以 1
开头而不是 0
,只需将其更改为:
<div class="testrun<?= $index + 1 ?>">