Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 15:06
Show Gist options
  • Save knolaust/224f87f84a5d209104856d9170133020 to your computer and use it in GitHub Desktop.
Save knolaust/224f87f84a5d209104856d9170133020 to your computer and use it in GitHub Desktop.
Custom endpoint for WP API returning multiple queries
<?php
/**
* Custom REST API Endpoint: Get Home Content
* Gist Keywords: wordpress, api, rest, content
*
* @category WordPress
* @author Knol Aust
* @version 1.0.0
* @description Retrieves featured content and the three most recent posts via a custom REST API endpoint. This example shows you can use one endpoint to pull in various queries from the API for a page like frontpage.
*/
function custom_rest_get_home_content( $params ){
// Query the featured content
$feature = get_posts([
'post_type' => 'page',
'pagename' => 'featured',
'post_status' => 'publish'
]);
// Get three most recent posts
$updates = get_posts([
'posts_per_page' => 3,
'post_status' => 'publish'
]);
$controller = new WP_REST_Posts_Controller('post');
$array = [];
foreach ( $updates as $update ) {
$data = $controller->prepare_item_for_response($update,$request);
$array[] = $controller->prepare_response_for_collection($data);
}
$home_content = array(
'feature' => $feature,
'latest' => $array
);
return $home_content;
}
// Register the custom REST route
add_action( 'rest_api_init', function () {
register_rest_route( '/custom/v1/', 'get-home-content',array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'custom_rest_get_home_content'
) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment