How to use a custom taxonomy term name as meta_value in a get_posts query

I am stuck with something which I am sure is simple, but I cannot find an answer online. I have two custom post types ('walks' and 'features') which I am trying to query using a code number which is unique to each 'walk'. 'Features' can relate to one or more 'walks' and this is stored on the 'features' cpt as a custom taxonomy 'feature-on-route-number'. I am trying to use the taxonomy value (or values) and to list the walk (or walks) that the feature relates to. The corresponding number stored on the 'walks' cpt in a custom field ('route_number') '. I have tried the following code: $routenumber = get_the_term_list( $post->ID, 'feature-on-route-number', '', ', ', '' ); $posts = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'walks', 'meta_key' => 'route_number', 'meta_value' => $routenumber )); This returns no results. I have tested the query by adding actual values for 'meta_value', and by assigning a single value to $routenumber and it works. So I am guessing the problem is with using a taxonomy to set the variable. Is there a simple way to fix this? Or do I need a second query to loop through the taxonomy? Many thanks

Comment (1)

Jese Leos

September 24, 2024

Verified user

Don't use get_the_term_list() WordPress function for that, as it gives an HTML string of linked term names. Use instead one of the following related WordPress functions: get_the_terms() wp_get_post_terms() Assuming that "feature-on-route-number" is the correct custom taxonomy, try: $routenumber = get_the_terms($post->ID, 'feature-on-route-number'); if ( $routenumber && !is_wp_error($routenumber) ) { $posts = get_posts( array( 'posts_per_page' => -1, 'post_type' => 'walks', 'meta_key' => 'route_number', 'meta_value' => current($routenumber)->name, )); } It should better work.

You’ll be in good company