Search code examples
wordpressisset

Show all wp_query posts before query filter


I'm trying to figure out how to filter properly wp_query. The code which I have currently works fine, but the outcome is - it shows no posts at the beginning. Only after filtering. So the issue is with validating the select input. I've tried multiple ways to achieve that, yet without success.

This is my code

 $args_main_query = array(
        'post_type' => 'newoldcars',
        'post_status' => 'publish',
        'posts_per_page' => -1, 
        'tax_query' => array(
            array(
            'taxonomy' => 'cars',
            'field'    => 'slug',
            'terms'    => $_POST["car_age"],
            ),
        ),

    );
$query = new WP_Query( $args_main_query );

how to do it properly??


Solution

  • What you need to do is only add the filtering when its been chosen...

    $args_main_query = array(
        'post_type'      => 'newoldcars',
        'post_status'    => 'publish',
        'posts_per_page' => -1 
    );
    if( isset($_POST["car_age"]) ) {
        $args_main_query['tax_query'] = array(
            array(
               'taxonomy' => 'cars',
               'field'    => 'slug',
               'terms'    => $_POST["car_age"],
            )
        );
    }
    $query = new WP_Query( $args_main_query );
    

    That way it only filters on car age when someone has selected a value.