K4S3
K4S3

Reputation: 163

WP_Query Not working or not displaying post content

I'm quite new to WordPress Development been following some online tuts and read bits and bobs of documentation but my WP_Query still displays nothing and when I add an else to my loop the else condition displays. I have created the page I'm trying to pull from the database what am I doing wrong here's the code:

<section id="home">
               <?php
               $query = new WP_Query( array( 'pagename' => 'home' ) );
               if ($query->have_post() ) {
                 while ($query->have_posts() ){
                   $query->the_post();
                   echo '<div class="entry-content">';
                   the_content();
                   echo '</div>';
                 }
               }
               wp_reset_postdata();
                ?>
             </section>

Upvotes: 2

Views: 2546

Answers (2)

Shital Marakana
Shital Marakana

Reputation: 2887

use the below code for display content

$args=array(
    'post_type' => 'post'

);
$the_query = null;
// the query
$the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>

    <!-- pagination here -->

    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <div class="entry-content"><?php the_content(); ?></div>
    <?php endwhile; ?>
    <!-- end of the loop -->

    <!-- pagination here -->

    <?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Upvotes: 0

Artsrun Hakobyan
Artsrun Hakobyan

Reputation: 112

simply change

$query->have_post()

to

$query->have_posts()

Upvotes: 1

Related Questions