简体   繁体   English

如果没有帖子可以显示,我该如何发送消息

[英]How do I throw a message if there are no posts to display

I am displaying an array of posts by the following code. 我通过以下代码显示帖子数组。 When there are no posts to display, I want to print a notification, eg "No posts to display". 如果没有要显示的帖子,我想打印一个通知,例如“没有要显示的帖子”。 How can this be done? 如何才能做到这一点?

<?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; ?>

In your example you would have to modify your code as follows: 在您的示例中,您将必须按如下所示修改代码:

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

have_posts() returns true when there are posts to display, and false when there aren't any (see the Documentation ). 当有要显示的帖子时, have_posts()返回true当没有帖子时返回false (请参见文档 )。

You can easily evaluate the value of this, and display your message accordingly. 您可以轻松评估此值,并相应显示您的消息。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM