jack
jack

Reputation: 403

Why does my Wordpress Query not work on non Index Pages?

I have this loop running on my Wordpress Index (index.php) page, which displays my posts with no problem.

But if I try to use this code on another page, no posts are found.

Can anyone explain why?

Ta!

    <?php
        $args = array(
            'post_type' => 'post',
                );
        $query = new WP_Query($args);
        if ( $query->have_posts() ) :
            // Start the Loop.
            while ( have_posts() ) : the_post();
                get_template_part( 'content', get_post_format() );

            endwhile;
            // Previous/next post navigation.
            twentyfourteen_paging_nav();

        else :
            get_template_part( 'content', 'none' );

        endif;
    ?>

Upvotes: 2

Views: 417

Answers (2)

AleksandarPredic
AleksandarPredic

Reputation: 51

Just some important points here:

Please add wp_reset_postdata(); after every custom Query. https://codex.wordpress.org/Function_Reference/wp_reset_postdata

Also, query only published posts. 'post_status' => 'publish'

<?php 
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => -1,
            'post_status' => 'publish'
                );
        $query = new WP_Query($args);
        if ( $query->have_posts() ) :
            // Start the Loop.
            while ( $query->have_posts() ):
                $query->the_post();
                get_template_part( 'content', get_post_format() );
            endwhile;
            // Previous/next post navigation.
            twentyfourteen_paging_nav();

            // Reset post data
            wp_reset_postdata();

        else :
            get_template_part( 'content', 'none' );

        endif;
    ?>

Upvotes: 1

Anjana Shyamlal
Anjana Shyamlal

Reputation: 408

Just done few edits to your code.Please try this. Worked for me.

<?php 
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => -1
                );
        $query = new WP_Query($args);
        if ( $query->have_posts() ) :
            // Start the Loop.
            while ( $query->have_posts() ):

        $query->the_post();
                get_template_part( 'content', get_post_format() );
                            endwhile;
            // Previous/next post navigation.
            twentyfourteen_paging_nav();

        else :
            get_template_part( 'content', 'none' );

        endif;
    ?>

Upvotes: 1

Related Questions