我正在尝试为WP REST API创建一个自定义端点,它应该包含某些ACF字段及其创建的选项,以防该字段是一个选择字段。
这是我在functions.php中尝试的代码
function test_get_acf() {
$field = get_field_object('credits');
$credits = array();
if( $field['choices'] ) {
foreach( $field['choices'] as $value => $label ) {
array_push($credits, $value);
}
}
$items = array(
'credits' => $credits
);
return $items;
}下面是创建端点的函数:
function test_register_api_endpoints() {
register_rest_route( 'test/v2', '/acf', array(
'methods' => 'GET',
'callback' => 'test_get_acf',
) );
}
add_action( 'rest_api_init', 'test_register_api_endpoints' );但是,这样做会得到以下JSON输出:
[
"credits": [ ]
]所以很明显它不起作用。我做错了什么?
发布于 2020-02-03 20:18:46
问题是ACF找不到你请求的字段,根据get_field_object() documentation的说法,它还接受一个post_id参数,这个参数默认为当前的帖子id,为了只获取字段对象(在帖子上下文之外),你应该像这样使用字段键:
$field = get_field_object('field_5e380cf7b4bf0');在本例中,field_5e380cf7b4bf0是字段的关键字。如果您必须使用此方法,并且还需要动态检索键,那么有一个here指令可以告诉您如何通过字段键的名称来获取它。
或者将示例帖子id传递给它:
global $wp_query;
$field = get_field_object('credits', $wp_query->posts[0]->ID); // Or just pass a number like 1 if you are sure that a post with that id exists注意:如果你刚创建了一个字段,但还没有任何帖子在使用它,那么当你调用get_field_object()时,它也可能导致false
https://stackoverflow.com/questions/60037420
复制相似问题