首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在WordPress REST API中获取自定义字段发布对象数据

如何在WordPress REST API中获取自定义字段发布对象数据
EN

Stack Overflow用户
提问于 2021-05-12 04:40:55
回答 1查看 53关注 0票数 0

我想知道如何使用WordPress Rest API从自定义字段获取Post对象数据。

这是我的JS:

代码语言:javascript
运行
复制
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。

我如何才能走得更远?

EN

回答 1

Stack Overflow用户

发布于 2021-05-13 03:35:46

这个问题的答案是创建一个自定义路由...

文件: routes/events-route.php

代码语言:javascript
运行
复制
<?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

代码语言:javascript
运行
复制
require_once 'routes/events-route.php';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67494056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档