为了账号安全,请及时绑定邮箱和手机立即绑定

自定义端点中按帖子 ID 分类 ID

自定义端点中按帖子 ID 分类 ID

PHP
30秒到达战场 2023-07-08 20:13:28
我为我的自定义帖子类型制作自定义端点。一件事是分类 ID。我需要通过帖子 ID 获取分类 ID。get_terms( 'gallery_tax', $post->ID )给我包含所有分类对象的数组function wl_posts() {    $args = [    'numberposts' => 9999,    'post_type' => 'gallery',  ];  $posts = get_posts($args);  $data = [];  $i = 0;  foreach ($posts as $post) {    $data[$i]['id'] = $post->ID;    $data[$i]['fimg_url'] = get_the_post_thumbnail_url($post->ID, 'large');    $data[$i]['proizvoditel'] = get_field('proizvoditel', $post->ID);    $data[$i]['tip'] = get_field('tip', $post->ID);    $data[$i]['razmer'] = get_field('razmer', $post->ID);    $data[$i]['forma'] = get_field('forma', $post->ID);    $data[$i]['rost'] = get_field('rost', $post->ID);    $data[$i]['ves'] = get_field('ves', $post->ID);    $data[$i]['ohvat'] = get_field('ohvat', $post->ID);    $data[$i]['vozrast'] = get_field('vozrast', $post->ID);    $data[$i]['galereya'] = get_field('galereya', $post->ID);    $data[$i]['taxonomy'] = get_terms( 'gallery_tax', $post->ID );    $i++;  }  return $data;}add_action('rest_api_init', function() {    register_rest_route('wl/v1', 'gallery', [        'methods' => 'GET',        'callback' => 'wl_posts',    ]);});
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

使用get_terms('gallery_tax')将为您提供分类法中的所有术语。


https://developer.wordpress.org/reference/functions/get_terms


您将获得分类中的所有现有术语。这就是你得到结果的原因。


使用get_the_terms($post->ID, 'gallery_tax')将为您提供帖子附带的所有分类术语。


https://developer.wordpress.org/reference/functions/get_the_terms/


您将获得分配给您的帖子的所有术语。


如果您想显示分类法本身的名称而不显示与帖子关联的术语,您可以首先在帖子循环之外获取所有分类法名称,然后在 foreach 内获取分类法名称:


...

$data = [];

$i = 0;

$taxnames = get_taxonomies('','names');


foreach ($posts as $post) {

    ...

    $data[$i]['taxonomy'] = wp_get_post_terms($post->ID, $taxnames, array("fields" => "names"));

    $i++;

}


...

https://developer.wordpress.org/reference/functions/get_taxonomies/


查看完整回答
反对 回复 2023-07-08
  • 1 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信