簡體   English   中英

WordPress循環,將特定類別添加到第二個帖子,第三次,重置,添加類別等

[英]Wordpress Loop, Add specific class to the 2nd post, 3rd, reset, add class etc

我試圖自定義自定義帖子類型並根據帖子的順序更改輸出。 我在下面有以下內容,但訂單輸出正常運行

輸出如下所示(在前3個帖子之后跳過):

  • 約翰·杜(John Doe),復古伯班克8
  • 約翰·杜(John Doe),古董伯班克(Vintage Burbank)7兩
  • 約翰·杜(John Doe),復古伯班克6
  • 約翰·杜(John Doe),復古伯班克5
  • 約翰·杜(John Doe),復古伯班克4
  • 約翰·杜(John Doe),復古伯班克3
  • 約翰·杜(John Doe),復古伯班克2
  • 約翰·杜(John Doe),古董伯班克(Vintage Burbank)1兩

我希望它像這樣出來:

  • 約翰·杜(John Doe),復古伯班克8
  • 約翰·杜(John Doe),古董伯班克(Vintage Burbank)7兩
  • 約翰·杜(John Doe),復古伯班克6
  • 約翰·杜(John Doe),復古伯班克5
  • 約翰·杜(John Doe),古董伯班克(Vintage Burbank)4兩
  • 約翰·杜(John Doe),復古伯班克3
  • 約翰·杜(John Doe),復古伯班克2
  • 約翰·杜(John Doe),古董伯班克(Vintage Burbank)1兩

      <?php $args = array( 'post_type' => 'testimonials', 'posts_per_page' => -1 ); $query = query_posts($args); ?> <?php $i = 1; while (have_posts()) : the_post(); ?> <?php if($i%3 == 0) : ?> <?php the_title();?> three <?php elseif($i%2 == 0) : ?> <?php the_title();?> two <?php else : ?> <?php the_title();?> <?php endif; ?> <?php $i++; ?> <?php endwhile;?> <?php wp_reset_query(); ?> 

為什么到處使用? 另外,當您獲得匹配項時,您需要重置$ i,它應該可以工作。 嘗試這個:

<?php
$args = array(
    'post_type' => 'testimonials',
    'posts_per_page' => -1
);

$posts = get_posts($args);
$i = 1;
foreach ($posts as $post) {
    setup_postdata($post);
    if($i%3 == 0) {
        echo get_the_title().' three';
        $i = 0;
    }
    elseif($i%2 == 0) {
        echo get_the_title().' two';
        $i = 0;
    }
    else {
        the_title();
    }
    $i++;
}
wp_reset_postdata();
?>

好的,我認為您的代碼還可以,唯一的問題是您對$i更新很差。 我已經修改了您的代碼,並且我認為它應該可以工作(如果不行,請通知我)。

<?php
$args = array(
    'post_type' => 'testimonials',
    'posts_per_page' => -1
);

$query = query_posts($args);
?>
<?php $i = 1;
while (have_posts()) : the_post(); ?>

    <?php if ($i % 3 == 0) : ?>

        <?php the_title(); ?> three

    <?php elseif ($i % 2 == 0) : ?>    

        <?php the_title(); ?> two

    <?php else : ?>

        <?php the_title(); ?> 

    <?php endif; ?>
    <?php  /* Comment this line */ ?>
    <?php /* $i++; */?>
    <?php /* Add this one */ ?>
    <?php $i = ($i >= 3) ? 1 : ($i + 1); ?>

<?php endwhile; ?>
<?php wp_reset_query(); ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM