Filter uncanny-automator

automator_rest_routes_user_response

Filters the response data for REST API user routes, allowing modification before it's sent.

add_filter( 'automator_rest_routes_user_response', $callback, 10, 1 );

Description

Filters the response data for user REST API requests. Developers can modify the user data returned by the API before it's sent to the client. This is useful for adding custom fields or altering existing user properties. It fires after user data is retrieved but before being sent.


Usage

add_filter( 'automator_rest_routes_user_response', 'your_function_name', 10, 1 );

Parameters

$request (mixed)
This parameter contains the WP_REST_Request object for the current user endpoint request.

Return Value

The filtered value.


Examples

<?php
/**
 * Example of using the 'automator_rest_routes_user_response' filter hook.
 *
 * This callback modifies the user response data returned by the REST API endpoint.
 * In this example, we're adding a custom field indicating if the user is an administrator.
 */
add_filter(
	'automator_rest_routes_user_response',
	function ( $user_data, WP_REST_Request $request ) {
		// Ensure we have valid user data before proceeding.
		if ( ! $user_data || is_wp_error( $user_data ) ) {
			return $user_data;
		}

		// Get the user object if it exists.
		if ( isset( $user_data['id'] ) && $user_id = absint( $user_data['id'] ) ) {
			$user = get_userdata( $user_id );

			if ( $user ) {
				// Add a custom field to the response indicating if the user is an administrator.
				$user_data['is_administrator'] = user_can( $user, 'manage_options' );
			}
		}

		// Return the modified user data.
		return $user_data;
	},
	10, // Priority.
	2   // Accepted arguments: $user_data, $request.
);

Placement

This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.


Source Code

src/core/services/rest-routes.php:110

'/user/(?P<id>d+)',
		array(
			// The permission callback.
			'methods'             => 'GET',
			'permission_callback' => $authentication,
			'callback'            => function ( WP_REST_Request $request ) {
				// And instantiate when needed.
				return apply_filters(
					'automator_rest_routes_user_response',
					( new User_Endpoint() )->find_by_id( $request )
				);
			},
		)
	);


Scroll to Top