使用wp_query检查第一篇文章

时间:2016-07-06 11:37:53

标签: php wordpress

我是wordpress的新手。在循环内部,我想检查帖子是否是查询的第一个结果。

这是我的代码。

<?php
    $args = array('post_type' => 'home-slider', 'posts_per_page' => 6, 'order' => 'ASC');
    $query = new WP_Query( $args );
    while ($query->have_posts()) : $query->the_post();
?>

<?php if (  ) { ?> // check if first post
    <p>TEST</p>
<?php } else { ?>
    <p>TEST123</p>
<?php } ?>

<?php
    endwhile;
?>

提前致谢。

3 个答案:

答案 0 :(得分:1)

尝试此代码 首先在while循环中定义$inc=1;

然后在循环if($inc==1)时检入然后打印您想要的内容并使用$inc++;增加$ inc值

<?php
    $args = array('post_type' => 'home-slider', 'posts_per_page' => 6, 'order' => 'ASC');
    $query = new WP_Query( $args );$inc=1;
    while ($query->have_posts()) : $query->the_post();
?>

<?php if ($inc==1 ) {$inc++; ?> // check if first post
    <p>TEST</p>
<?php } else { ?>
    <p>TEST123</p>
<?php } ?>

<?php
    endwhile;
?>

答案 1 :(得分:1)

您可以将其移至外部并在if()语句后查询第一篇帖子,而不是在循环内部进行检查:

<?php
    $args = array('post_type' => 'home-slider', 'posts_per_page' => 6, 'order' => 'ASC');
    $query = new WP_Query( $args );
?>

<?php if ($query->have_posts()) : $query->the_post(); ?>

    <p>TEST</p>

<?php
    endif;
    while ($query->have_posts()) : $query->the_post();
?>

    <p>TEST123</p>

<?php endwhile; ?>

答案 2 :(得分:0)

WP_Query对象具有一个current_post field, which is actually a counter,从0开始计数。

<?php
    $args = array('post_type' => 'home-slider', 'posts_per_page' => 6, 'order' => 'ASC');
    $query = new WP_Query( $args );$inc=1;
    while ($query->have_posts()) : $query->the_post();
?>

<?php if ($query->current_post==0) { ?> // check if first post
    <p>TEST</p>
<?php } else { ?>
    <p>TEST123</p>
<?php } ?>

<?php
    endwhile;
?>
相关问题