Aalok Amalmani
Aalok Amalmani

Reputation: 57

have_posts() return false in wordpress

I'm trying to show the last article on my theme for wp, so I wrote this code:

<?php get_header(); ?>

<div class="content">

<div class="pad group">

    <?php get_template_part('inc/page-title'); ?>

    <?php //echo var_dump(have_posts()); ?>

    <?php if ( have_posts() ) : ?>

        <?php if ( ot_get_option('blog-standard') == 'on' ): ?>

            <?php while ( have_posts() ): the_post(); ?>
                <?php get_template_part('content-standard'); ?>
            <?php endwhile; ?>

        <?php else: ?>
            <div class="post-list group">
                <?php $i = 1; echo '<div class="post-row">'; while ( have_posts() ): the_post(); ?>
                    <?php get_template_part('content'); ?>
                    <?php if($i % 2 == 0) { echo '</div><div class="post-row">'; } $i++; endwhile; echo '</div>'; ?>
            </div><!--/.post-list-->
        <?php endif; ?>

        <?php get_template_part('inc/front-widgets-bottom'); ?>
        <?php get_template_part('inc/pagination'); ?>
        <?php get_template_part('inc/picks'); ?>

    <?php endif; ?>

    <?php get_template_part('inc/front-widgets-top'); ?>

</div><!--/.pad-->

in the first part I get the header, in the content div I've opened a container called pad group and then with page-title I get the title of the page.

After this I check if there is post available (of course there are) with if ( have_posts() ), but the code in the condition is never executed, infact if you see I did a var_dump of have_posts() and this return false.

I saw already other question here with the same topic but I cannot find any solution for me. Some of these questions ask about a if condition not properly closed but I checked all the files included (header also) and I can't find any problem.

Someone maybe have a better eye than me? Thanks for any help.

Upvotes: 0

Views: 5893

Answers (2)

Prince
Prince

Reputation: 186

try this-

$args = array(
    'post_type' => 'post',//or you can add custom post type
    'order' => 'DESC'
);
$posts = get_posts($args);
if(!empty($posts)){
    foreach($posts as $post => $post_val){
        echo $post_val->post_content;
    }
}

Upvotes: 0

Jędrzej Skrzypczak
Jędrzej Skrzypczak

Reputation: 138

Try to use custom WP_Query.

// WP_Query arguments
$args = array(
    'posts_per_page'         => '1',
    'cat' => <CATEGORY_ID>
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // do something
    }
} else {
    // no posts found
}

// Restore original Post Data
wp_reset_postdata();

Code above will fetch one recent post from category you set via CATEGORY_ID.

If you like to further customise you query, you can use WP_Query generator, or check WP_Query Class docs.

Upvotes: 1

Related Questions