繁体   English   中英

如何在 WordPress REST ZDB974238714CA8DE63ZF7ACED1 中获取自定义字段帖子 Object 数据

[英]How do I get Custom Field Post Object data in WordPress REST API

我想知道如何使用 WordPress Rest ZDB934423871861Z Rest ZDB9344238718ADE.CECE84A8 从自定义字段中获取 Post Object 数据

这是我的 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()

它返回 object,但 class_type 的高级自定义字段作为示例返回 ID 字符串,即该事件的 Class 帖子类型 ID。

在此处输入图像描述

我怎样才能走得更远?

在此处输入图像描述

答案是创建一个自定义路由......

文件: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;

将路由添加到您的函数中。php

文件:functions.php

require_once 'routes/events-route.php';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM