• Resolved midiriders

    (@midiriders)


    Heya,

    I’m working on a custom theme and the simple PHP function I’m using to determine if a post exists isn’t working. Any idea why this might be?

    <?php if(have_posts()) : ?>
         post found
     <?php else : ?>
         <?php echo wpautop('Sorry, no posts were found'); ?>
     <?php endif; ?>

    The only post is the default “Hello World!”.

    This code displays “post found” whether I’ve deleted the post, or the post is active.

    I don’t get the “Sorry, no posts were found” message after moving the post to the trash. I’ve cleared my cache.

    Appreciate any help

Viewing 4 replies - 1 through 4 (of 4 total)
  • You need to include whole loop.
    In this article you can find everything you need:
    The Loop

    P.s. you use wpautop in wrong context. If you want to output/echo some strings, you should use localize function like this:
    Escaping with Localization

    Moderator bcworkz

    (@bcworkz)

    In addition to using The Loop, have_posts() works in context with the main, global query object. If your code occurs on a single page template for example, the main query is for that page and the status of other posts like Hello World are irrelevant.

    For have_posts() to work for blog posts, the main query has to be for a blog archive.

    Thread Starter midiriders

    (@midiriders)

    Thanks for the tips & heads up, appreciated guys!

    Thread Starter midiriders

    (@midiriders)

    For the record, I’m sure this can be far more eloquent but it works…

    $wp_query = new WP_Query( array ( 'posts_per_page' => -1 ) );
     if ( have_posts() ) : while ( have_posts() ) : the_post(); 
        echo "Post exists";
     endwhile; else :
        esc_html_e( 'Sorry, no posts exist.' );
     endif;

    Thanks again –

    • This reply was modified 5 years, 8 months ago by midiriders.
    • This reply was modified 5 years, 8 months ago by midiriders.
Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘have_posts() inaccurate output’ is closed to new replies.