I need to add more arguments to the wp_query if they variables are !empty when passed by the shortcode. I am passing the name of a couple of custom field names to be used in the loop.
I want it to work like this: If custom_field_1 is !empty but custom_field_2 is empty, add the first array to the $args array. If custom_field_1 is !empty and custom_field_2 is !empty, add the second array to the $args array.
I feel that I am somewhere in the ballpark but it is not working properly. If I manually add each of the meta_queries to the $args array it returns the correct data.
Any help would be appreciated.
// Attributes
extract( shortcode_atts(
array(
'pagination' => 'true',
'query' => '',
'category' => '',
'tag_name' => '',
'custom_field_1' => '',
'custom_field_2' => '',
'relation_operator' => '',
'number_posts' => '',
'order_by' => '',
'order' => '',
), $atts ));
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$custom_field_query = array ();
// if $custom_field_1 is not empty and $custom_field_2 is empty
if (!empty($custom_field_1) && empty($custom_field_2) ) {
array_push($custom_field_query, array (
'meta_query' => array(
array(
'key' => $custom_field_1,
'value' => '',
'compare' => '!='
) ) ) );
}
// if $custom_field_1 is not empty and $custom_field_2 is not empty
if (!empty($custom_field_1) && !empty($custom_field_2) ) {
array_push($custom_field_query, array (
'meta_query' => array(
'relation' => $relation_operator,
array(
'key' => $custom_field_1,
'value' => '',
'compare' => '!=',
),
array(
'key' => $custom_field_2,
'value' => '',
'compare' => '!=',
) ) ) );
}
// if $custom_field_query has array custom_field_query gets added to $args
if(!empty($custom_field_query)){
$args['custom_field_query'] = $custom_field_query;
}
// WP_Query arguments
$args = array(
'paged' => $paged,
'post_type' => array( 'page', ' post' ),
'post_status' => array( 'publish' ),
'category_name' => $category,
'tag' => $tag_name,
'category__in' => $theCatId,
'posts_per_page' => $number_posts,
'order' => $order,
'orderby' => $order_by,
);
// The Query
global $wp_query,$paged,$post;
$my_query = new WP_Query( $args );
$args['custom_field_query']
isn't a valid query argument, that should be$args['meta_query']
. Check out the php manual for working with associative arrays,array_push
is not the function for that.