Introduction to the WP_REST_Widgets_Controller Class in WordPress

wordpress wp rest widgets controller
25 June 2025

Familiarity with WP_REST_Widgets_Controller

The WordPress library includes various classes that are responsible for managing different sections of the site. One of these classes is WP_REST_Widgets_Controller, which allows us to work with widgets via the WordPress REST API. You may want to easily manage and control widgets through codes, and this class provides the necessary capabilities for this task.

Something to keep in mind is that WP_REST_Widgets_Controller allows you to send requests to the server, add, remove, and update widgets. In larger projects, this capability is necessary to conveniently manage widgets via the API. In other words, you can use this class to improve the interaction space with widgets.

In the code below, you will see an example of the functions related to this class. The functions of this class help us to register widgets and send requests to the server. Additionally, this code demonstrates how to register these widgets with the REST API.

Code Example

function my_register_widget_routes() {
register_rest_route('myplugin\/v1', '/widgets', array(
'methods' => 'GET',
'callback' => 'my_get_widgets',
));
}
add_action('rest_api_init', 'my_register_widget_routes');

function my_get_widgets() {
return array(
'widget-1' => 'First Widget',
'widget-2' => 'Second Widget',
);
}

Code Explanation


Code: function my_register_widget_routes() {
This function is designed to register new routes in the REST API.

Code: register_rest_route('myplugin\/v1', '/widgets', array(...));
In this line, a new route is registered to the API that uses the GET method to retrieve widgets.

Code: add_action('rest_api_init', 'my_register_widget_routes');
This line connects the my_register_widget_routes function to the action 'rest_api_init' so that this function executes when the API is initialized.

Code: function my_get_widgets() {
This function is designed to return a list of registered widgets.

Code: return array('widget-1' => 'First Widget', 'widget-2' => 'Second Widget');
In this line, an array consisting of widgets is returned, which can be observed in the API responses.

FAQ

?

What is the purpose of WP_REST_Widgets_Controller?

?

How can I add a new widget?

?

Can I remove widgets via the API?

?

How can I retrieve widget information?