have_post() does return null value in wp

2.3k Views Asked by At

I used the following code in my page template:

<?php
while(have_posts()):the_post();
the_content();
?>

But nothing is displayed. The loop is not working. I'm sure that, there is sufficient information as content in my template page.

3

There are 3 best solutions below

4
Deep Kakkar On BEST ANSWER

You should use if condition to check if post exists else skip the loop. Make sure to ON the error log and check the exact error.

<?php wp_reset_query(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
0
Mayeenul Islam On
<?php
/**
* Template Name: My Template
*/

the_post();
the_content();
?>

If you save the following code as a page template and call the page template into a page by choosing it, then the page will show the page content without any hassle.

Note: it's THE minimal bit of code.

0
sarath On

use the following code Try using wp_reset_query()

 <?php
    wp_reset_query();
    while(have_posts()):the_post();
    the_content();
    endwhile;
   ?>