[英]Adding post fields to post data in custom WordPress REST API endpoint
I have a custom field that I have added to every wordpress post.我有一个自定义字段,已添加到每个 wordpress 帖子中。 I created an api endpoint that queries posts where the custom field is a certain value.我创建了一个 api 端点,用于查询自定义字段为特定值的帖子。 That works great, the code is:效果很好,代码是:
function fp_acf() {
$args = array(
'meta_key' => 'featured_post',
'meta_value' => 'yes'
);
$the_query = new WP_Query( $args );
return $the_query;
}
add_action('rest_api_init', function() {
register_rest_route('wp/v2', 'featured_posts', array(
'methods' => array('GET', 'POST'),
'callback' => function() {
return fp_acf();
},
));
});
The Problem:问题:
The data that is returned from that endpoint doesn't contain all of the post data that is typically included in, say "/wp/v2/posts", specifically the slug or link.从该端点返回的数据不包含通常包含在“/wp/v2/posts”中的所有发布数据,特别是 slug 或链接。
Question:题:
I am wondering if it is possible to add the slug of the posts returned in this question query endpoint to the post data being returned?我想知道是否可以将此问题查询端点中返回的帖子的 slug 添加到正在返回的帖子数据中?
If I understood the problem correctly and under the presumption that you are using the ACF plugin, going by the function name fp_acf
, you will want to register a custom REST field that contains the value of your desired ACF field.如果我正确理解了问题,并假设您正在使用 ACF 插件,函数名称为fp_acf
,您将需要注册一个包含所需 ACF 字段值的自定义 REST 字段。
To get this done you have to do the following:要完成此操作,您必须执行以下操作:
WP_Query
is going over have the ability to be shown in the REST api.首先,确保WP_Query
正在处理的所有帖子都能够显示在 REST api 中。'show_in_rest' => true
to their register_post_type
argument array.默认帖子和页面已显示在 REST api 中,但对于任何自定义帖子类型,您需要将'show_in_rest' => true
到其register_post_type
参数数组。rest_api_init
callback like so:接下来,您要实际注册自定义 REST 字段,在您的rest_api_init
回调中执行此操作,如下所示:add_action('rest_api_init', function() {
// ...
register_rest_field( array( 'your_post_type' ), 'is_featured_post', array(
'get_callback' => function() {
return get_field('featured_post');
},
'schema' => array(
'description' => 'Shows whether the post is featured',
'type' => 'string'
),
));
});
Obviously, you can change the return
value of the get_callback
function to whatever you need.显然,您可以将get_callback
函数的return
值更改为您需要的任何值。 You should be able to use all of the same functions, such as get_the_permalink
, get_the_title
etc. as you would when looping over posts in a template.您应该能够使用所有相同的函数,例如get_the_permalink
、 get_the_title
等,就像在模板中循环帖子时一样。
NB you say you need to get the slug of the posts, you should find that there already is a slug
property that is returned by the REST api for posts and pages.注意,您说您需要获取帖子的 slug,您应该发现 REST api 已经为帖子和页面返回了一个slug
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.