KodeFor.Me
KodeFor.Me

Reputation: 13511

WP_Query() Fatal error: Call to a member function have_posts() on a non-object in ...single-diapers.php on line 82

I have the following very strait forward code, but it doesn't work. I have write queries like that many many times, but this time I am faced with a very strange problem.

$args = array (
    'post_type'              => 'diapers',
    'post_status'            => 'publish',
    'posts_per_page'         => '3'
);

$products = new WP_Query( $args );

if ( $products->have_posts() ) {

?>
<div class="more-products">
    <div class="col-xs-12 col-md-4">
        <h3 class="more-products-title text-center text-md-right">
            <?php
                _e('more products', 'z');
            ?>
        </h3>
    </div>
    <div class="col-xs-12 col-md-8">
        <div class="row">
            <?php
                while ( $products->have_posts() ) {
                    $products->the_post();
            ?>
                <div class="col-xs-12 col-md-4">
                    <?php the_title(); ?>
                </div>
            <?php
                }
            ?>
        </div>
    </div>
</div>
<?php
}

But I am getting the following error :

Fatal error: Call to a member function have_posts() on a non-object in /var/www/projects/no-company/wp-content/themes/babies/single-diapers.php on line 82
Call Stack
#   Time    Memory  Function    Location
1   0.0000  234248  {main}( )   .../index.php:0
2   0.0001  234696  require( '/project-path/wp-blog-header.php' )   .../index.php:17
3   0.0302  2471776 require_once( '/project-path/wp-includes/template-loader.php' ) .../wp-blog-header.php:16
4   0.0374  2594376 include( '/project-path/wp-content/themes/babies/single-diapers.php' )  .../template-loader.php:74

Is there anyone that can see something wrong with this code ? I have try, but I can't see anything that's wrong with this code.

In addition, you should know, that I have try to print_r the $products right before the while ( $products->have_posts() ) and the $products contains data.

Also, I have try the print_r inside the loop, after the $products->the_post() and in the first loop I have normal the data inside the object, but in the second loop, I get as result a 0.

Finally, I have also use the same code structure to another template file in my code and works, but this particular one doesn't wont to work :(

Upvotes: 0

Views: 1335

Answers (1)

You can stop the error message with the following (but it still does not solve the not an object problem).

if ( is_object($products) && $products->have_posts() ) {

This will mean that if the code fails like this for other people it will not give them a fatal error. However, you still need to find out why you do not have an object when you were expecting one.

Upvotes: 2

Related Questions