Skip to content
Advertisement

WordPress: passing $query to separate template file

I have the following code:

homepage.php

<?php
    $query = new WP_Query(
        array(
            'order'       => 'ASC',
            'orderby'     => 'menu_order',
            'post_type'   => 'work'
        )
    );
?>
<?php get_template_part('loop', 'feed-work'); ?>
<?php wp_reset_query(); ?>

loop-feed-work.php

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

But when I view my homepage, I get the following error:

Fatal error: Uncaught Error: Call to a member function have_posts() on null in ******/loop-feed-work.php:1

Could this be because the query is in a different template file?

Advertisement

Answer

That’s exactly the problem. Unfortunatly get_template_part doens’t work like an include so you will lose the scope variable when inside the included file. The solution to that problem while mantaining the same logic is to change get_template_part and use:

// $templates[] = "{$slug}-{$name}.php"; // This is how wp builds the slug iside get_template_part
include locate_template('loop-feed-work.php');
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement