How do I dynamically generate args for wp_query?

I am trying to build up my search args depending on variables passed through from a form.

What I want to do is add to args if values are present.

For example if there are dates I have:

$args = array(
    'date_query' => array(
        array(
        'after'     => $datestart,
        'before'    => $dateend,
        'inclusive' => true,
        ),
    ),
);

}

and if there is a search query then I will have:

$args = array( 
  'post_type'   => 'post',
  's' => $search_query,
);

I have tried using

$args[]

to combine the arrays but that doesn’t seem to work in this instance.

I have also tried

 array_push 

and that doesn’t seem to work for me either.

I seem to end up with something that looks like this:

array(2) {
    [0]=>
    array(1) {
    ["date_query"]=>
    array(1) {
    [0]=>
    array(3) {
    ["after"]=>
    string(10) "2015-01-01"
    ["before"]=>
    string(10) "2016-12-01"
    ["inclusive"]=>
    bool(true)
    }
    }
}
    [1]=>
    array(2) {
    ["post_type"]=>
    string(4) "post"
    ["s"]=>
    string(7) "lecture"
    }
}

I am sure there must be something obvious I am missing!

Any ideas will be appreciated!

0

Leave a Comment