John Davidson

php - How do I use a tax_query and a meta_query in wordpress succesfully?

0 comments
Message:


This is the code I am using:


$results = array(
'post_type' => 'score',
'tax_query' => array(
array(
'taxonomy' => 'competitions',
'field' => 'slug',
'terms' => $tax->slug,
'compare' => '='
)
),
'meta_query' => array(
array(
'numberposts' => -1,
'post_type' => 'score',
'meta_key' => 'horse_name',
'meta_value' => $horsename,
'compare' => 'LIKE'
)
)
);

// query
$the_query = new WP_Query($results);

The problem is I can't work out how to make a Boolean AND expression so that both the taxonomy and the custom field should match before returning a post.



My Answer:
To use a tax_query and a meta_query in WordPress successfully with a Boolean AND expression, you need to modify your code as follows:

php
$results = array(
'post_type' => 'score',
'tax_query' => array(
array(
'taxonomy' => 'competitions',
'field' => 'slug',
'terms' => $tax->slug,
'compare' => '='
)
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'horse_name',
'value' => $horsename,
'compare' => 'LIKE'
)
)
);

// query
$the_query = new WP_Query($results);


In the meta_query array, you need to add a 'relation' key with the value 'AND' to specify that both conditions should be met. Also, change 'meta_key' to 'key' and remove 'numberposts' and 'post_type' keys as they are not needed in the meta_query.

With these changes, the query will only return posts that match both the taxonomy and the custom field criteria.

Rate this post

4 of 5 based on 2854 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us