【问题标题】:Wordpress loop add a specific class to each 3 posts in the loopWordpress 循环为循环中的每 3 个帖子添加一个特定的类
【发布时间】:2016-04-29 00:51:03
【问题描述】:

我正在使用特定循环在 Wordpress 的自定义页面上显示 3 个帖子。我想为每个帖子添加一个类。

帖子 1:.post-1

帖子 2:.post-2

帖子 3:.post-3

我有这个循环:

<div class="news-wrap">
<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
<div class="news-item">
    <div class="news-title"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></div>
    <span class="news-date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
    <?php html5wp_excerpt('html5wp_index'); // Build your custom callback length in functions.php ?>
</div>

我不完全确定在这个循环中要改变什么,因为我对 php 很陌生。我在 Wordpress 论坛上找到了以下解决方案,但代码完全不同。

<?php if (have_posts()) : ?>
<?php $c = 0;while (have_posts()) : the_post(); $c++;
if( $c == 3) {
$style = 'third';
$c = 0;
}
else $style='';?>
<div <?php post_class($style) ?> id="post-<?php the_ID(); ?>"

我想我可以为 1、2、3 和我想要的类编写 if 语句,但我不知道从哪里开始我当前的循环。

【问题讨论】:

    标签: php wordpress class loops posts


    【解决方案1】:

    试试这个代码:

    <div class="news-wrap">
    <?php
    $args = array( 'numberposts' => 3 );
    $lastposts = get_posts( $args );
    $index = 0;
    foreach($lastposts as $post) : setup_postdata($post); ++$index; ?>
    <div class="news-item post-<?php echo $index; ?>">
        <div class="news-title"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></div>
        <span class="news-date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
        <?php html5wp_excerpt('html5wp_index'); // Build your custom callback length in functions.php ?>
    </div>
    

    不确定在哪里需要“.post-#”类,所以我已将它们添加到“.news-item”元素中。

    我在存储当前数组索引的位置添加了 $index 变量。它从 0 开始,但在循环开始时(在 foreach 开始时),我将 index 的值增加 1。

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多