如何注册基于 REST 路由中现有值的自定义字段

How to register custom field that is based on existing value in REST route

我正在注册一条休息路线(参见代码 1),其中路线的内容将等于 wpso_messages 数据库中的结果。

自定义路由的 get 请求的结果 JSON 如下。 (参见#Resultant Json)

我想在其余路由中注册 2 个额外的自定义字段,它们是:,它们基​​于当前在(参见结果 JSON)。

我知道我可能必须使用 register rest field 函数(参见示例代码 2),但是它似乎并没有挂钩到已注册的自定义 rest 路由,另外,我需要访问 user_from 现有 api 回调中的列。

有什么建议吗?

#代码 1:注册休息路线

<?php

 function get_wp_query() {
    global $wpdb;
      $row = $wpdb->get_results("SELECT * FROM wpso_messages");
      return $row;
      };
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );

#结果JSON

{ “编号”:“1”, "user_from": "82", "user_to": "1", "created_at": "2022-01-07 10:25:56", "message": "我有兴趣出价", "listing_id": "22775", “看到”:“1” }

代码 2:

function get_custom_fields() {
    return 'our awesome endpoint';
}
add_action( 'rest_api_init', 'add_custom_fields' );

function add_custom_fields() {
    register_rest_field(
        'messages', 
        'custom_fields', //New Field Name in JSON RESPONSEs
        array(
            'get_callback'    => 'get_custom_fields', // custom function name 
            'update_callback' => null,
            'schema'          => null,
            )
        );
    }

在您的 get_wp_query() 函数中,不要立即 return 结果。首先,遍历它们并从那里添加必填字段。

你的情况:

function get_wp_query() {
   global $wpdb;
   $rows = $wpdb->get_results("SELECT * FROM wpso_messages");

   foreach( $rows as $index => $row ) {
        $rows[$index]->username_from = get_user_by('id', $row.user_from)->display_name;
        $rows[$index]->username_to = get_user_by('id', $row.user_to)->display_name;
   }
   return $rows;
};

基于解决方案的 Nawaz 提议:

function get_wp_query() {
    global $wpdb;
    $rows = $wpdb->get_results("SELECT * FROM wpso_messages");
    foreach( $rows as $index => $row ) {
    
           $user_from_id = $rows[$index]->user_from; 
           $user_to_id = $rows[$index]->user_to; 
           $rows[$index]->username_from = get_user_by('id', $user_from_id)->display_name;
           $rows[$index]->username_to = get_user_by('id', $user_to_id)->display_name;
    }
    return $rows;
};


add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );