How do I fetch the static front page using the REST API?

We could implement our own endpoint:

https://example.tld/wpse/v1/frontpage

Here’s a simple demo (PHP 5.4+):

<?php
/** 
 * Plugin Name: WPSE - Static Frontpage Rest Endpoint
 */
namespace WPSE\RestAPI\Frontpage;

\add_action( 'rest_api_init', function()
{
    \register_rest_route( 'wpse/v1', '/frontpage/', 
        [
            'methods'   => 'GET',
            'callback'  => __NAMESPACE__.'\rest_results'
        ] 
    );
} );

function rest_results( $request )
{
    // Get the ID of the static frontpage. If not set it's 0
    $pid  = (int) \get_option( 'page_on_front' );    

    // Get the corresponding post object (let's show our intention explicitly)
    $post = ( $pid > 0 ) ? \get_post( $pid ) : null;  

    // No static frontpage is set
    if( ! is_a( $post, '\WP_Post' ) )
        return new \WP_Error( 'wpse-error', 
           \esc_html__( 'No Static Frontpage', 'wpse' ), [ 'status' => 404 ] );

    // Response setup
    $data = [
        'ID'      => $post->ID,
        'content' => [ 'raw' => $post->post_content ]
    ];

    return new \WP_REST_Response( $data, 200 );     
}

A successful response is like:

{"ID":123,"content":{"raw":"Some content"}}

and an error response is like:

{"code":"wpse-error","message":"No Static Frontpage","data":{"status":404}}

Then we can extend it to support other fields or rendered content by applying the the_content filter.

Leave a Comment