我想知道如何使用WordPress Rest API从自定义字段获取Post对象数据。
这是我的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()
它返回对象,但class_type的高级自定义字段作为示例返回ID的字符串,这是该事件的类发布类型Id。
我如何才能走得更远?
发布于 2021-05-13 03:35:46
这个问题的答案是创建一个自定义路由...
文件: 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;
将路由添加到您的functions.php
文件: functions.php
require_once 'routes/events-route.php';
https://stackoverflow.com/questions/67494056
复制相似问题