Search code examples
phpwordpress

How to get correct post_count and found_posts within include file


I have created an include file which allows me to filter my post queries using a category dropdown. I am trying to get the post_count and found_posts dynamically so I can display Showing 6 out of 12 Posts for example. I am including this filter on a custom page template with a custom WP_Query, but I am getting Showing 1 out of 1 Posts despite there being 10+ posts. I believe the reason it is doing this is because the filter include is using the single page query rather than my custom post query. How can I go about updating this so that the filter uses my custom post query?

inc/filter.php:

<?php
    global $wp_query;
    $count = $wp_query->post_count;
    $total = $wp_query->found_posts;
?>

<div class="container">
    <div class="row">
        <div class="col">
            <?php $get_categories = get_categories(); ?>
            <select>
                <option selected disabled>Select category</option>
                <option value="all">All</option>
                <?php
                    if ($get_categories) :
                        foreach ($get_categories as $cat) :
                    ?>
                    <option value="<?php echo $cat->term_id; ?>">
                        <?php echo $cat->name; ?>
                    </option>
                    <?php endforeach; 
                        endif;
                    ?>
            </select>
            <div class="shown-posts">Showing <span class="visible-posts"><?php echo $count; ?></span> of <span class="total-posts"><?php echo $total; ?></span> posts</div>
        </div>
    </div>
</div>

And here's my custom page template:

<?php get_header();?>
<?php 
    $posts = new WP_Query(array(
        'post_type' => 'post'
    ));
?>
<?php if($posts->have_posts()): ?>
    // Here's where I'm including the filter file
    <?php get_template_part( 'inc/filter' ); ?>
    <div class="container post-container">
        <div class="row row-eq-height">
            <?php while ($posts->have_posts()) : $posts->the_post();
                the_title();
            endwhile; ?>
        </div>
    </div>
<?php endif; ?>

Solution

  • The correct way to pass variable to templates included via get_template_part() is to add them to the WordPress query_vars.

    So in inc/filter.php remove all of this...

    <?php
        global $wp_query;
        $count = $wp_query->post_count;
        $total = $wp_query->found_posts;
    ?>
    

    Then in the main template add...

    <?php 
        $posts = new WP_Query(array(
            'post_type' => 'post'
        ));
    
        set_query_var( 'count', $posts->post_count );
        set_query_var( 'total', $posts->found_posts );
    ?>