0

I'm trying to filter paginated results of my custom query. I've got 4 posts, 3 per page, total of 2 pages. When I apply the filter while on page 1, it works. When I apply the filter while on page 2, query result is empty.

My guess is either query doesn't know which page I'm on or I got the form action="" wrong. Any hints?

<div class="row justify-content-md-center">
    <div class="col-9 m-4 pt-4 pb-4">
        <form action="" method="get">
            <label>Select option</label>
            <select name="filter_options">
                <option value="">Any</option>
                <option value="800">800</option>
                <option value="1200">1200</option>
            </select>
            <button type="submit" class="btn btn-primary">Filter</button>
        </form>
    </div>
</div>

<div class="row justify-content-md-center">
<?php
     $currentPage = get_query_var( 'paged', 1 );

     if (array_key_exists('filter_options', $_GET)) {
          $value = $_GET['filter_options'];
          $args = array(
              'post_type'=> 'my_custom_type',
              'paged' => $currentPage,
              'posts_per_page'=>3,
              'meta_query' => array(
                  'relation' => 'OR',
                   array(
                        'meta_key' => 'my_meta_key',
                        'value' => $value)
                    )
                );
     } else {
          $args = array(
             'post_type'=> 'my_custom_type',
             'paged' => $currentPage,
             'posts_per_page'=>3
          );
    }

    $posts = new WP_Query($args);

    if ($posts->have_posts()) {
        while ($posts->have_posts()) {
            $posts->the_post();
            get_template_part( '/template-parts/content', 'filters');
        }
    }
    wp_reset_query();
?>
</div>

<div class="row justify-content-md-center mt-5">    
    <div class="col-2">
            <?php echo paginate_links(array(
                'total' => $posts->max_num_pages,
                'prev_text' => 'Prev',
                'next_text' => 'Next'
            )); ?>
    </div>
</div>
0

It's a custom dynamic page, used only for this specific query result. The problem was form action="" being empty. $_GET parameters were sent to the same page i.e. /result-page/?filter-options=800 which is fine but while on page-2, the results were sent to /result-page/page/2/?filter-options=800.

Setting the form action="/result-page" solved the problem. Thanks.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.