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.
You will either need to globalize
$books
(if you want to stick toget_template_part()
) or useinstead of
get_template_part( 'loop', 'books' );
. This issue is caused by$books
inloop-books.php
being defined only in the scope ofget_template_part()
.An alternate method: open/close the loop, and then use
loop-books.php
to contain just the markup for the loop content. e.g.:Then, inside of
loop-books.php
: