skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    Thank you LoicTheAztec for the code edit. It worked to produce one result, but missed multiple terms. I added a taxonomy loop and it seemed to work. Not sure if this is the most elegant approach though.

                $terms = wp_get_post_terms( $post->ID, 'feature-on-route-number' );
                foreach( $terms as $term){
                $routenumber = $term->name;             
                $posts = get_posts(array(
                'posts_per_page'    => -1,
                'post_type'         => 'walks',
                'meta_key'      => 'route_number',
                'meta_value'    => $routenumber                                    
                ));
    

    // processes on the results }


  2. 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,              
        ));
    }
    

    It should better work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search