6

I would like to create an Angular 2 SPA that uses the WordPress REST API as a back-end. How can I use the API to fetch the page the user has set as their front page?

2
  • 1
    What have you tried so far? Are you asking how to create a custom REST endpoint in a plugin, or are you asking how to get the page the user has set as the frontpage in code? ( If the answer is both, you will want to ask 2 separate questions for maximum effectiveness, we have a 1 question per question policy here )
    – Tom J Nowell
    Nov 13, 2016 at 17:05
  • The later, I was wondering if it was possible to programmatically fetch the page that is configured to be the static front page. I have just got it working actually by using an additional plugin I'll post the code up now.
    – Connel
    Nov 13, 2016 at 17:07

4 Answers 4

8

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.

4
  • What's up with the \back_slashes?
    – jgraup
    Nov 13, 2016 at 22:11
  • When using namespace, I use it to access the global functions and classes, but hat's not always neccessary. For example if I would define my own get_post() function, then I would have to use \get_post() to call the WordPress core version. If I don't define my own get_post(), then get_post() will call the WordPress core function. WordPress is currently not using any namespace either. I decided to backslash mostly everyting here , just for the sake of consistancy, since this is just a small code snippet ;-) @jgraup
    – birgire
    Nov 13, 2016 at 22:31
  • I figured for namespaces, just didn't ever think of redefining something like 'get_post' unless on a class. Learn something new each day.
    – jgraup
    Nov 13, 2016 at 22:37
  • Sometimes it's handy to define a function with a short handy name that's already taken. I guess there's also a fine line between consistancy and "backslash spam" ;-) Usually I just do it when it's neccessary, somehow the "consistancy" urge got hold of me here ;-) @jgraup
    – birgire
    Nov 13, 2016 at 22:45
2

Because I build several Polymer & Angular SPA's for the frontend with WordPress backends I've created a plugin for this purpose https://wordpress.org/plugins/wp-rest-api-frontpage/

I hope this helps...

Basically it extends the native REST API with a new route:

wp-json/wp/v2/frontpage

Cheers!

2
  • 1
    Congratulation with your plugin release. Few remarks: 1) probably better to use own namespace instead of wp/v2 that's used by core 2) same goes for the WP_ class prefix 3) file_get_contents() adds extra request and might not always work for url requests 4) there's still a wpse textdomain and wpse-error used in the code that doesn't match the wp-rest-api-frontpage plugin text domain. cheers
    – birgire
    May 10, 2017 at 14:41
  • @birgire: Thanks for the quick 'code-review'. Will definitely take it into account! May 15, 2017 at 7:03
2

This happens to be very simple. WordPress doesn't have frontpage endpoint by default but you can create one like this.

// Register Front Page route.
// URL will be: domainname.ext/wp-json/my-namespace/v1/frontpage/
register_rest_route(
  'my-namespace/v1', '/frontpage',
  array(
      'methods'  => 'GET',
      'callback' => [ $this, 'get_frontpage' ],
  )
);


// Callback function.
function get_frontpage( $object ) {

  // Get WP options front page from settings > reading.
  $frontpage_id = get_option('page_on_front');

  // Handle if error.
  if ( empty( $frontpage_id ) ) {
    // return error
    return 'error';
  }

  // Create request from pages endpoint by frontpage id.
  $request  = new \WP_REST_Request( 'GET', '/wp/v2/pages/' . $frontpage_id );

  // Parse request to get data.
  $response = rest_do_request( $request );

  // Handle if error.
  if ( $response->is_error() ) {
     return 'error';
  }

  return $response->get_data();
}
1

I have just got this working using the plugin 'WP API Options' plugin. You can find the plugin here: https://en-gb.wordpress.org/plugins/wp-rest-api-options/

It allows you to see which page has been configured as the front page. Below is a TypeScript code snippet that uses the 'wp-api-angular' package.

getFrontPage(): Promise<any> {
    return this.wpApiPages
      .httpGet('/options/page_on_front')
      .toPromise()
      .then(response => response.json())
      .then(body => body.page_on_front)
      .then(frontPageId => this.wpApiPages
        .get(frontPageId)
        .toPromise()
        .then(response => response.json()))
      .catch(error => {});
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.