函数文档

register_rest_field()

💡 云策文档标注

概述

register_rest_field() 函数用于在 WordPress REST API 中为现有对象类型(如文章、分类、评论等)注册自定义字段。它允许开发者通过回调函数定义字段的获取、更新逻辑和模式,扩展 API 响应数据。

关键要点

  • 核心功能:向 WordPress 对象类型(如 post、term、comment)添加自定义字段,使其在 REST API 响应中可用。
  • 参数说明:$object_type 指定对象类型(字符串或数组),$attribute 为字段名,$args 数组包含 get_callback、update_callback 和 schema 等选项。
  • 回调函数:get_callback 用于获取字段值,接收对象数据;update_callback 用于更新字段值,接收模型对象(如 WP_Post)和值;schema 定义字段模式,可包含 arg_options 用于验证和清理。
  • 使用场景:常用于扩展文章元数据、添加特色图像源、处理自定义表查询等,需通过 rest_api_init 钩子调用。
  • 注意事项:update_callback 的参数顺序可能随 WordPress 版本变化(如值、对象、字段名),需参考最新文档;get_callback 的参数可能包括对象数组、属性名、请求对象和对象类型。

代码示例

add_action('rest_api_init', function() {
    register_rest_field('post', 'my_field', array(
        'get_callback' => function($object) {
            return get_post_meta($object['id'], 'my_field', true);
        },
        'update_callback' => function($value, $object) {
            update_post_meta($object->ID, 'my_field', $value);
        },
        'schema' => array(
            'type' => 'string',
            'arg_options' => array(
                'sanitize_callback' => function($value) {
                    return sanitize_text_field($value);
                },
                'validate_callback' => function($value) {
                    return (bool) preg_match('/A[a-z]{10}Z/', $value);
                }
            )
        )
    ));
});

注意事项

  • 确保在 rest_api_init 钩子中调用 register_rest_field(),以保证 API 初始化时注册字段。
  • 注意回调函数参数的正确顺序和类型,避免因版本差异导致错误,如 update_callback 的参数顺序可能为 $value, $object, $fieldName。
  • 使用 schema 的 arg_options 可添加 sanitize_callback 和 validate_callback 来增强数据安全性和验证。
  • 对于自定义对象类型(如自定义文章类型或分类法),直接使用其名称作为 $object_type 参数。

📄 原文内容

Registers a new field on an existing WordPress object type.

Parameters

$object_typestring|arrayrequired
Object(s) the field is being registered to, “post”|”term”|”comment” etc.
$attributestringrequired
The attribute name.
$argsarrayoptional
An array of arguments used to handle the registered field.

  • get_callback callable|null
    Optional. The callback function used to retrieve the field value. Default is 'null', the field will not be returned in the response. The function will be passed the prepared object data.
  • update_callback callable|null
    Optional. The callback function used to set and update the field value. Default is 'null', the value cannot be set or updated. The function will be passed the model object, like WP_Post.
  • schema array|null
    Optional. The schema for this field.
    Default is 'null', no schema entry will be returned.

Default:array()

Source

function register_rest_field( $object_type, $attribute, $args = array() ) {
	global $wp_rest_additional_fields;

	$defaults = array(
		'get_callback'    => null,
		'update_callback' => null,
		'schema'          => null,
	);

	$args = wp_parse_args( $args, $defaults );

	$object_types = (array) $object_type;

	foreach ( $object_types as $object_type ) {
		$wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
	}
}

Changelog

Version Description
4.7.0 Introduced.

User Contributed Notes

  1. Skip to note 9 content

    GET callbacks accept up to 4 arguments in order…

    • $post – (object) Post or custom post type object of the request.
    • $attr – (string) Rest field/attr string identifier from the second parameter of your register_rest_field() declaration.
    • $request – (object) Full request payload – as a WP_REST_Request object
    • $object_type – (string) The object type which the field is registered against. Typically first parameter of your register_rest_field() declaration.

    Post callbacks accept the above arguments but also a 5th argument in the first position which is the value being passed from the POST request to the attribute/field.

  2. Skip to note 10 content

    To make use of sanitize_callback and validate_callback, pass those in arg_options in schema

    // Make sure to use PHP >= 5.4
    add_action(
    	'rest_api_init',
    	function () {
    		// Field name to register.
    		$field = 'my_field';
    		register_rest_field(
    			'post',
    			$field,
    			array(
    				'get_callback'    => function ( $object ) use ( $field ) {
    					// Get field as single value from post meta.
    					return get_post_meta( $object['id'], $field, true );
    				},
    				'update_callback' => function ( $value, $object ) use ( $field ) {
    					// Update the field/meta value.
    					update_post_meta( $object->ID, $field, $value );
    				},
    				'schema'          => array(
    					'type'        => 'string',
    					'arg_options' => array(
    						'sanitize_callback' => function ( $value ) {
    							// Make the value safe for storage.
    							return sanitize_text_field( $value );
    						},
    						'validate_callback' => function ( $value ) {
    							// Valid if it contains exactly 10 English letters.
    							return (bool) preg_match( '/A[a-z]{10}Z/', $value );
    						},
    					),
    				),
    			)
    		);
    	}
    );

  3. Skip to note 11 content

    An example to add all of the post meta to a post-meta-fields field:

    add_action( 'rest_api_init', 'create_api_posts_meta_field' );
    
    function create_api_posts_meta_field() {
    
    	// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    	register_rest_field( 'post', 'post-meta-fields', array(
    	       'get_callback'    => 'get_post_meta_for_api',
    	       'schema'          => null,
    	    )
    	);
    }
    
    function get_post_meta_for_api( $object ) {
    	//get the id of the post object array
    	$post_id = $object['id'];
    
    	//return the post meta
     	return get_post_meta( $post_id );
    }

    This can be extended or edited. For example, if you don’t want to include all the post meta, you can filter it, or return only the field you need. The options are limitless, but the callback gives you access to the post object, which exposes the id among other parameters, so you can use many different helper functions.

  4. Skip to note 12 content

    This code works (also with shipped Backbone client) in WordPress 4.9.4:

    $meta = [
        'key' => 'my_post_type_name',
        'description' => 'This is the name of my post type',
        'type' => 'string'
    ];
    
    register_rest_field('my_post_type', $meta['key'], [
        'get_callback' => function ($params) use ($meta) {
            return get_post_meta($params['id'], $meta['key'], true);
        },
        'update_callback' => function ($value, $object, $fieldName){
            return update_post_meta($object->ID, $fieldName, $value);
        }
    ]);

  5. Skip to note 13 content

    An example to add post featured image src to the ‘featured_image_src’ field.

    add_action( 'rest_api_init', function () {
    	register_rest_field( 'post', 'featured_image_src', array(
    		'get_callback' => function ( $post_arr ) {
    			$image_src_arr = wp_get_attachment_image_src( $post_arr['featured_media'], 'medium' );
    
    			return $image_src_arr[0];
    		},
    		'update_callback' => null,
    		'schema' => null
    	) );
    } );

    Helpful for showing featured image in gutenberg block development when posts are fetched with withSelect() function.

  6. Skip to note 14 content

    Custom sql queries can be achieved to get whatever value you want from database. The following queries shows how can we modify rest output to show something from our custom table ‘wp_it_job_details’ which is, of course, inside WordPress database. Put it in your themes/plugins functions.php

    function add_last_date_data() {
      //Last date
      register_rest_field( 'post',
        'last_date',
        array(
            'get_callback'  => 'rest_get_last_date',
            'update_callback'   => null,
            'schema'            => null,
         )
      );
    }
    function rest_get_last_date( $object ) {
        //get the Post Id
        $post_id = $object['id'];
    	global $wpdb;
    	$sql = "SELECT * FROM wp_it_job_details WHERE post_id = '$post_id'"; //wp_it_job_details is job table
    	$results = $wpdb->get_row($sql);
    		if(count($results) > 0) {
    			//We have this post_id row in the table
    			return $results->last_date;	//last_date is the column name, change to your's
        
    		} else return ""; //return nothing 
    		
        
    }
    add_action( 'rest_api_init', 'add_last_date_data' );

  7. Skip to note 15 content

    The $object_type parameter is a little unclear from this description unless you go digging or understand the broader context of how the REST API handles object types (string|array required Object(s) the field is being registered to, “post”|”term”|”comment” etc.).

    If you are registering an additional REST field for a specific taxonomy’s terms, simply enter the name of the taxonomy. For example, this registers the field ‘website’ for the taxonomy named ‘post-author’.

    add_action('rest_api_init', function() {
        register_rest_field('post-author', 'website', array(
            'get_callback' => function($term) {
                return 'https://example.com/...'; // Insert your actual logic to fetch the field here
            },
        ));
    });

  8. Skip to note 16 content

    // assume there custom post_type named events 
    add_action( 'rest_api_init', function() {
        register_rest_field( 'events', 'event_date', array(
    
            'get_callback' => function( $comment_arr ) {
                $comment_obj = get_field('event_date', $comment_arr['id'] );
                return $comment_obj;
            },
    
            'update_callback' => function( $karma, $comment_obj ) {
                update_field('event_date', $karma, $comment_arr['id'] );
                return true;
            },
    
            'schema' => array(
                'event_date' => __( 'event_date' ),
                'type'        => 'text'
            ),
    
        ));
    
    });