phpwordpresscustom-post-typecustom-taxonomytaxonomy-terms

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              
));

// processes on the results

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


Solution

  • 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:

    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,              
        ));
    
        // processes on the results
    }
    

    It should better work.


    Addition (handling one or multiple terms)

    It is possible to handle an array of meta values by defining the meta_compare argument to "IN" for that meta query.

    Also when using wp_get_post_terms() you can define the returned terms as term names directly, using the third function argument.

    The code:

    $routenumbers = wp_get_post_terms($post->ID, 'feature-on-route-number', ['fields' => 'names']); 
    
    if ( $routenumbers && !is_wp_error($routenumbers) ) {
        $posts = get_posts( array(
            'posts_per_page'    => -1,
            'post_type'         => 'walks',
            'meta_key'          => 'route_number',
            'meta_value'        => $routenumbers,   
            'meta_compare'      => 'IN',              
        ));
    
        // processes on the results
    }