Post Filtering by GET URL parameters

Question

I am trying to add a simple filter for posts in my wordpress site by setting parameters in the URL, however it is simply not filtering the posts which is driving me crazy. All the tutorials or forums dont show what happens if the URL isnt filtering your posts.

My posts have categories (Test, windows and WordPress) that I would like to learn to filter, e.g. it would have checkboxes for each category type. However, when the URL is set as /sites/?orderby=date&order=DESC&category%5B%5D=windows it isnt changing anything that is displayed?

If someone could help me out to understand why its not filtering the posts that would be appreciated.

My code:

    <form method="GET">

    <select name="orderby" id="orderby">
        <option
                value="date"
            <?php echo selected($_GET['orderby'], 'date'); ?>
        >
            Newest to Oldest
        </option>
        <option
                value="title"
            <?php echo selected($_GET['orderby'], 'title'); ?>
        >
            Alphabetical
        </option>
    </select>

    <input
            id="order"
            type="hidden"
            name="order"
            value="<?php echo (isset($_GET['order']) && $_GET['order'] == 'ASC') ? 'ASC' : 'DESC'; ?>"
    />


    <?php

    $terms = get_terms([
        'taxonomy' => 'category',
        'hide_empty' => false
    ]);

    foreach ($terms as $term) :

        ?>

        <label>

            <input
                    type="checkbox"
                    name="category[]"
                    value="<?php echo $term->slug; ?>"
                <?php checked(
                    (isset($_GET['category']) && in_array($term->slug, $_GET['category']))
                ) ?>
            />

            <?php echo $term->name; ?>

        </label>

    <?php endforeach; ?>


    <button type="submit">Apply</button>

</form>

<div class="wrapper">

    <?php
    $arg = array(
        'type' => 'post',
        'order' => 'ASC'
    );
    $blog_posts = new WP_Query( $arg );

    if ($blog_posts->have_posts()) :

        while( $blog_posts->have_posts() ) : $blog_posts->the_post();

            echo the_title();
            echo "<br>";

        endwhile;

    endif;
    ?>

</div>
0
, , Thomas 3 years 2020-06-07T08:11:05-05:00 0 Answers 70 views 0

Leave an answer

Browse
Browse