如何通过术语ID WordPress获取自定义帖子的有限或特定字段



我使用了下面的查询:

$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/>';

它工作正常。但我的要求是只获取post namepost ID.这可能吗?如果是,那我们该怎么做呢?

您可以使用

返回字段 https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter

更新的参数如下。

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

但这里没有返回标题的选项。希望对您有所帮助。

只需编写一个函数即可遍历查询结果并获取所需的数据

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

最新更新