Sidebar endpoint using WordPress API

I cannot find any info on this. Is there a default endpoint for sidebars?

For example pages:

http://localhost:8888/example/wp-json/wp/v2/pages

I have looked at the WordPress API documentation but don’t see any endpoints for sidebars or widgets.

I also tried something basic like this:

function sidebar_api( $data ) {
    
    $response_body = get_sidebar('one');
    return new WP_REST_Response(
        array(
            'body_response' => $response_body
        )
    );
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'custom/v1', 'sidebar1', array(
        'methods'  => 'GET',
        'callback' => 'sidebar_api',
    ) );
} );

which gives me the sidebar not in json format and then a json response with an empty body_response.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Is there a default endpoint for sidebars?

No, I don’t think there is. So (for now), using a custom REST API endpoint does sound like a good option to me.

gives me the sidebar not in json format and then a json response with an empty body_response

That’s because get_sidebar() echo the output, hence the $response_body is empty.

So you’d want to use output buffering like so:

ob_start();
get_sidebar( 'one' );
$response_body = ob_get_clean();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x