2

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();
1

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);
1
<?php 
global $wp_query;
$meta_query = array();
$queryGenre = $_GET['genre'];
$mood = $_GET['mood'];
$paged = get_query_var('paged', 1);
if($queryGenre):
    $meta_query[] = array(
        array(
            'key' => 'genre',
            'value' => $queryGenre,
            'compare' => '='
        ),
    ); 
endif;

if($mood):
    $meta_query = array('relation' => 'AND');
    $meta_query[] = array(
        array(
            'key' => 'mood',
            'value' => $mood,
            'compare' => '='
        ),
    ); 
endif;

$loop = new WP_Query( array(
    'posts_per_page' => 5,
    'post_type'      => 'catalog',
    'paged'          => $paged,
    'order_by'       => 'ASC',
    'meta_query'     =>$meta_query
));
if($loop->have_posts()):
while ( $loop->have_posts() ) : $loop->the_post();
    //add your code here
endwhile;
endif; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.