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

时间:2019-01-10 13:55:26

标签: php wordpress post custom-post-type

我已使用以下查询:

$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。 这可能吗?如果是,那我们该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以使用返回字段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
 )
 )
);

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

答案 1 :(得分:0)

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

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