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:

<?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.

2 s
2

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().

Leave a Comment