2

I have a custom post type called Location with a custom field called City. I also have taxonomies on that post type called Specialties. The specialty filter works just fine with the tax_query, but I can't get the custom field to filter.

This is not working, and neither is just about everything else I've been trying:

$args = array('post_type' => 'location',
    'tax_query' => array(
          array(
          'taxonomy' => 'specialties',
          'field'    => 'slug',
          'terms'    => $specialty,
        )),
    'meta_query' => array(array('city' => $location,'compare' => '=',))
    );
1

Your 'meta_query' value is wrong - it should be:

'meta_query' => array(
    array(
        'key'     => 'city',
        'value'   => $location,
        'compare' => '=',
    )
);

Anyway, you don't need to use 'meta_query' in this case where you have to filter by just one meta field... So for a little more optimized code, try replacing your $args with the following:

$args = array(
    'post_type' => 'location',
    'tax_query' => array(
        array(
            'taxonomy' => 'specialties',
            'field'    => 'slug',
            'terms'    => $specialty,
        )
    ),
    'meta_key'  => 'city',
    'meta_value'=> $location,
);
  • Thanks! I'm going to need to add one more field so probably need to get it working with 'meta_query'? I tried this, and I get no results. $args = array('post_type' => 'location', 'tax_query' => array( array( 'taxonomy' => 'specialties', 'field' => 'slug', 'terms' => $specialty, )), 'meta_query' => array( array( 'key' => 'city', 'value' => $location, 'compare' => '=', )) ); – Von Aug 13 '17 at 20:15
  • @Von, if you have more than one field, then yes, you have to use 'meta_query'... I check and recheck the $args in my answer and I can't find any error... If it doesn't work, I'd say it's because of the rest of your code. For example, ensure $location and $specialty holds a correct value, check your action hook, etc... – ClemC Aug 13 '17 at 20:51
  • I couldn't make the custom field work in time so I just switched them all over to taxonomies and it worked like a charm. Thanks for the help. – Von Aug 14 '17 at 20:21

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.