How to get limited or specific fields of custom posts by term id WordPress?

Viewed 1214

I have used below query:

$args = array(
'post_type' => 'blogs',
'tax_query' => array(
    array(
    'taxonomy' => 'blog',
    'field' => 'term_id',
    'terms' => $backendEngineering->term_id
     )
  )
);
$responseData = new WP_Query( $args );
echo '<br/>';
print_r($responseData);
echo '<br/>';

It's working fine. But My requirement is to fetch only post name and post ID. Is this possible? If it is then how can we do it?

2 Answers

You can get using return fields https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter

Updated argument is following.

$args = array(
'post_type' => 'blogs',
 'fields'=>'ids',
'tax_query' => array(
array(
'taxonomy' => 'blog',
'field' => 'term_id',
'terms' => $backendEngineering->term_id
 )
 )
);

But here no option to return the title. Hope it will help you.

just write a function to loop through the query results and get the data you need

function echo_post_title_and_id(){
   $args = array(
   'post_type' => 'blogs',
   'tax_query' => array(
       array(
       'taxonomy' => 'blog',
       'field' => 'term_id',
       'terms' => $backendEngineering->term_id
        )
     )
   );
   $responseData = new WP_Query( $args );

      if ( $responseData->have_posts() ) {
              while ( $$responseData->have_posts() ) {
                     $responseData->the_post();
                      echo get_the_title();
                      echo get_the_id();
             }
      }else {
           echo 'no posts found';
      }
       wp_reset_postdata();
}
Related