Wordpress Rest API - 自定义字段 [英] Wordpress Rest API - Custom Fields

查看:73
本文介绍了Wordpress Rest API - 自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Wordpress 中创建了一个自定义帖子类型并将其公开给 rest API.我还使用 ACF 插件向这篇文章添加了自定义字段.

I have created a custom post type in Wordpress and exposed it to rest API. I have also added custom fields to this post using the ACF plugin.

在我的主题 function.php 中,我在响应中注册了这些字段,当我发出 get 请求时我可以看到它们.

In my themes function.php I have registered these fields in the response and I can see them when I make a get request.

register_rest_field('auto', 'specs', array('get_callback' => 'get_autos_specs_for_api'));

问题是当我发送 post 请求时,wordpress 无法识别这些字段.它创建了一个带有标题的新帖子,所有额外的字段都是空的.

The problem is that when I send a post request, wordpress doesn't recognize these fields. It creates a new post with the title and all the extra fields are empty.

推荐答案

对我来说,诀窍是将自己挂钩到其余的准备帖子,然后将您的字段添加到数组中,然后返回响应对象.

For me what did the trick was to hook yourself to the rest prepare post and then add your fields to the array, then return the response object.

function slug_add_data($response, $post) {

    $response->data['latitud'] = get_field('latitud', $response->data['id']);
    $response->data['longitud'] = get_field('longitud', $response->data['id']);

    return $response;
}

add_filter('rest_prepare_post', 'slug_add_data', 10, 3);

这篇关于Wordpress Rest API - 自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆