Using a custom WP_Query with get_template_part loop

I have a query for a custom post type:

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$books = new WP_Query(array(
    'post_type' => 'wiki',
    'posts_per_page' => '50',
    'paged' => $paged
));
?>

And i want to loop through these posts using the loop-books.php:

Read More
<?php get_template_part( 'loop', 'books' ); ?>

Inside the loop-books.php i have these, just like the regular loop.php, i just changed the have_posts and the_post function to work with the $books query:

<?php if ( $books->have_posts() ) : ?>      
    <?php while ($books->have_posts()) : $books->the_post(); ?>
        <?php the_title(); ?><br/>
    <?php endwhile; ?>
<?php endif; ?>

But after this, i get a php error:

Fatal error: Call to a member function have_posts() on a non-object in .../loop-books.php on line 1

So looks like the $books variable is not available inside the get_template_part function. How can i resolve this issue? If i put the $books query inside the loop-books.php its working fine, but i want to separate them.

Related posts

Leave a Reply

2 comments

  1. You will either need to globalize $books (if you want to stick to get_template_part() ) or use

    require( locate_template( 'loop-books.php' ) );
    

    instead of get_template_part( 'loop', 'books' );. This issue is caused by $books in loop-books.php being defined only in the scope of get_template_part().

  2. An alternate method: open/close the loop, and then use loop-books.php to contain just the markup for the loop content. e.g.:

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    // Get books query
    $books = new WP_Query(array(
        'post_type' => 'wiki',
        'posts_per_page' => '50',
        'paged' => $paged
    ));
    // Open books loop
    if ( $books->have_posts() ) :     
        while ($books->have_posts()) : $books->the_post();
            // Get loop markup
            get_template_part( 'loop', 'books' );
    // Close books loop
        endwhile;
    endif;
    ?>
    

    Then, inside of loop-books.php:

    <?php the_title(); ?><br/>