Home Forums Front-end Issues How to query taxonomies by custom field Reply To: How to query taxonomies by custom field

  • Hi Trestian

    As far as I’m aware there’s no way to natively query taxonomies by custom meta (yet – think this is being mooted for inclusion in core –

    So, you could cook up some SQL based query but they’re not really something I’m much cop at so an alternative would be to get the id for the location term you are interested in finding vendors for and then looping through all your vendors, matching any with a location that is the same as your search location. You could check the matches into an array then iterate over that to display them.

    The code below isn’t tested or anything – it’s really just to get you headed in the right direction. I should also point out that it’s a bit of a clunky way round the problem, particularly if you have loads of vendors – there may well be a much simpler way to do this I’m not aware of. However it should do the trick.

    $location_term = get_term( 'london', 'location' ); // Get term object for your chosen location
    $vendors = get_terms('vendors'); //Get all terms in vendors
    $matching_vendors = array(); // Create blank array for storing matching vendors
    foreach ($vendors as $vendor){ //Loop through all vendors
    	$vendor_location = get_field('vendor_location', $vendor->term_id);//Get term object for the location associated with this vendor.  Please note that off the top of my head I can't recall the object structure that is returned.  I think it might be the same as the regular get_term object in which case the below should be correct
    	if($vendor_location){ //Just check this variable exists
    		if($vendor_location->term_id == $location_term->term_id){ // If the vendor location ID matches the ID for the location you are interested in...
    			$matching_vendors[] = $vendor;//Add this vendor term object to you array
    // You can then do what you like with regard to your matched vendors:
    	foreach($matching_vendors as $vendor ){
    		// Do stuff to list out your matched vendors