How to get term by custom term meta and taxonomy or how to filter tax_query
by term meta instead slug
/id
?
function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
How to get term by custom term meta and taxonomy or how to filter tax_query
by term meta instead slug
/id
?
function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
Share
Improve this question
asked Jul 1, 2016 at 16:18
SeviSevi
3152 gold badges4 silver badges8 bronze badges
3 Answers
Reset to default 23Try This:
$args = array(
'hide_empty' => false, // also retrieve terms which are not used yet
'meta_query' => array(
array(
'key' => 'feature-group',
'value' => 'kitchen',
'compare' => 'LIKE'
)
),
'taxonomy' => 'category',
);
$terms = get_terms( $args );
Building on the answer from ilgıt-yıldırım above, both the get_term_meta
statement and $key == 'meta_value'
statements need to contain $term>term_id
.
Here's a complete example including the custom $wp_query
request:
$term_args = array( 'taxonomy' => 'your-taxonomy' );
$terms = get_terms( $term_args );
$term_ids = array();
foreach( $terms as $term ) {
$key = get_term_meta( $term->term_id, 'term-meta-key', true );
if( $key == 'term-meta-value' ) {
// push the ID into the array
$term_ids[] = $term->term_id;
}
}
// Loop Args
$args = array(
'post_type' => 'posts',
'tax_query' => array(
array(
'taxonomy' => 'your-taxonomy',
'terms' => $term_ids,
),
),
);
// The Query
$featured = new WP_Query( $args );
You'll need to loop through each of the terms in your main query conditional. Assuming there will likely be more than one term with the custom data, you'll then need to pass an array of IDs into your tax query.
For example, looping through each term to check for custom meta:
$term_args = array(
'taxonomy' => $taxonomy_name,
);
$terms = get_terms( $term_args );
$term_ids = array();
foreach( $terms as $term ) {
$key = get_term_meta( $term->ID, 'meta_key', true );
if( $key == 'meta_value' ) {
// push the ID into the array
$term_ids[] = $term->ID;
}
}
Then you end up with the variable $term_ids which contains an array of the term IDs you're looking for. You can pass that to your tax query.