如果没有要显示的帖子,如何抛出消息

时间:2013-04-09 14:43:14

标签: php wordpress if-statement

我通过以下代码显示一系列帖子。当没有要显示的帖子时,我想打印一个通知,例如“没有要发布的帖子”。怎么办呢?

<?php
    while ( have_posts() ) :
        the_post();
?>
        <h1><?php the_title();?></h1>
        <section class="intro">
        <?php the_content(); ?> 
        </section>
<?php endwhile; // end of the loop. ?>
        <h2>Latest Events</h2>

<?php
    query_posts( array( 'category__and' => array(8) ) );
    if ( have_posts() ) while ( have_posts() ) :
        the_post(); 
?>

        <article class="events clearfix">
            <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
            <?php the_excerpt(); ?>
            <div class="date">
                <span class="month"><?php the_time('M') ?></span>
                <span class="day"><?php the_time('d') ?></span>
            </div>
        </article>


<?php endwhile; ?>

2 个答案:

答案 0 :(得分:1)

在您的示例中,您必须按如下方式修改代码:

// Display latest events
// ...
if ( have_posts() ) {
    // ...
} else {
    echo '<article class="events clearfix">';
    echo '<p>No posts to display.</p>';
    echo '</article>';
}

答案 1 :(得分:0)

当有要显示的帖子时,

have_posts()会返回true;如果没有,则会false(请参阅Documentation)。

您可以轻松评估此值,并相应地显示您的消息。例如:

if(!have_posts())
{
    echo 'No posts to display&hellip;';
}
else
{
    // code to display your posts here.
}
相关问题