[英]How do I get Custom Field Post Object data in WordPress REST API
I'm wondering how I can get the Post Object data from a custom field with WordPress Rest API.我想知道如何使用 WordPress Rest ZDB934423871861Z Rest ZDB9344238718ADE.CECE84A8 从自定义字段中获取 Post Object 数据
Here's my JS:这是我的 JS:
import axios from 'axios'
const getEvents = () => {
return axios
.get('https://127.0.0.1/wp-json/wp/v2/events')
.then(res => {
console.log(res)
return res
})
.catch(err => {
console.error(err)
})
.then({})
}
getEvents()
It returns the object, but the Advanced Custom Fields for class_type as an example returns a string of the ID, which is the Class post type Id for that Event.它返回 object,但 class_type 的高级自定义字段作为示例返回 ID 字符串,即该事件的 Class 帖子类型 ID。
How can I get further?我怎样才能走得更远?
The answer to this is to create a custom route...答案是创建一个自定义路由......
File: routes/events-route.php文件:routes/events-route.php
<?php
class Events_Rest_Router {
public function __construct() {
$this->register_routes();
}
protected function register_routes() {
add_action('rest_api_init', function () {
$namespace = 'api/v1/';
register_rest_route($namespace, '/events', array(
'methods' => 'GET',
'callback' => array( $this, 'get_events' ),
));
});
}
public function get_events($request) {
$output = array();
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_key' => 'start_date',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$query = new WP_Query($args);
if ($query -> have_posts()) {
while ($query -> have_posts()) {
$query->the_post();
$post = get_post(get_the_ID());
if ($request['type'] == $post->location) {
array_push($output, array(
'id' => $post->ID,
'class_type' => get_field('class_type')
));
}
}
}
wp_reset_postdata();
return $output;
}
}
new Events_Rest_Router;
Add the route to your functions.php将路由添加到您的函数中。php
File: functions.php文件:functions.php
require_once 'routes/events-route.php';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.