I have the following function:
function returnD($p, $t1, $t2, $t3) {
$args = array(
'post_type' => $p,
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $t1,
'value' => 'up',
'compare' => '=',
)
)
);
$loop = new WP_Query( $args );
return $loop;
}
How can I modify the $args
meta_query
so that if
$t1
, $t2
, $t3
have no values there are no meta_query
added
otherwise for each $t#
, an array is added to meta_query
.
I am just trying to make it dynamic because not every call will have all three $t#
.
How can I achieve it?
You can dynamically build the
meta_query
array depending on the values that are passed in. In the code below,$t#
parameter passed in$t#
parameters then we use these arrays to build our meta query.$args
array without the meta_query argThe full function is below, and the code is commented:
Note that this isn't tested, but the basic idea is there. Also, you didn't say if this is an
AND
orOR
meta_query so I've built it using AND, but you can change as required.UPDATE: If you have a default meta_query, then you can add it to the meta_query array and args as normal. Then there is no need for the conditional statements to check
if ($meta_query)
in step 4 above.