WP_Query based on URL parameters

I’m looking for some help in creating a query based on fields I made in Advanced Custom Fields. I’d like to create a query that would loop through a custom post type, using arguments such as:

?genre=Dance&keyword=&mood=&album=

What I expect from this query is all posts with the genre meta-field of “Dance” to be posted. Since all of the other arguments have no value, I’m expecting these to be ignored in the query. If the arguments change to:

?genre=Dance&keyword=&mood=happy&album=

I want the query to narrow down and only find posts with the genre meta-field of “Dance” and the mood meta-field of “Happy”.

Here’s the code I’m using that gives me some of the results. The only way to add my mood variable to the query is if I use ‘AND’ as the relation and add it as another array, but then I lose being able to just query using one argument.

$queryGenre = $_GET['genre'];
$paged = get_query_var( 'paged' );
$loop = new WP_Query( array(
    'posts_per_page' => 5,
    'post_type'      => 'catalog',
    'paged'          => $paged,
    'order_by'       => 'ASC',
    'meta_query'     => array( 
        array(
            'key'     => 'genre',
            'value'   => $queryGenre,
            'compare' => '=',
        ) 
    )
) );
while ( $loop->have_posts() ) : $loop->the_post();

2 Answers
2

Try like this

 $meta_query = array('relation' => 'AND');
 if($queryGenre)
   {
    $query_genre = array(
        'key'     => 'genre',
        'value'   => $queryGenre,
        'compare' => '=',
    ) ;
     array_push($meta_query,$query_genre);
   }
   if($queryMood)
   {
    $query_mood = array(
        'key'     => 'mood',
        'value'   => $queryMood,
        'compare' => '=',
    ) ;
     array_push($meta_query,$query_mood);
   }

and at the end do

array_push($args,$meta_query);

Leave a Comment