Home > Enterprise >  How to Get The Taxonomy Term in Custom Post Type Loop Inside a Wp Query
How to Get The Taxonomy Term in Custom Post Type Loop Inside a Wp Query

Time:11-30

I need to get the term of each post while running WP Query. I tried this inside the loop

$term = $loop->get_queried_object();
echo  $term->name; 

but I am still getting custom Post Type registered name instead of getting the Term!

$args = array(  
        'post_type' => 'services',
        'post_status' => 'publish',
        'posts_per_page' => 8, 
        'orderby' => 'title', 
        'order' => 'ASC', 
    );

    $loop = new WP_Query( $args ); 
        
    while ( $loop->have_posts() ) : $loop->the_post(); 

     $term = $loop->get_queried_object();
     echo  $term->name; 

     echo  get_the_title(); 

endwhile;
wp_reset_postdata(); 

CodePudding user response:

You can use get_the_terms. try the below code.

$args = array(  
    'post_type' => 'services',
    'post_status' => 'publish',
    'posts_per_page' => 8, 
    'orderby' => 'title', 
    'order' => 'ASC', 
);

$loop = new WP_Query( $args ); 
    
while ( $loop->have_posts() ) : $loop->the_post(); 

    $terms = get_the_terms( get_the_ID(), 'your-custom-taxonomy-name' );
    $terms = join(', ', wp_list_pluck( $terms , 'name') );

    echo $terms;

    echo  get_the_title(); 

endwhile;
wp_reset_postdata();
  • Related