Marinus Klasen

Marinus Klasen

  • Development
  • Consultancy
  • Developer Resources
  • Blog
  • Contact

May 18, 2022

Using the WordPress REST API

Marinus Klasen

The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API.

Registering routes

Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers.

<?php
/**
* Plugin Name: Register REST Route Example
*/
add_action( 'rest_api_init', function() {
    // Register route for GET: example.com/wp-json/example/v1/action
    register_rest_route( 'example/v1', '/action', array(
        'methods' => 'GET',
        'callback' => function($request) {
            return $request->get_params();
        },
    ));	
});

This is everything you need to register a new endpoint in the REST API. The example above returns the parameters that you send as an example, so you can experiment and see what data our REST endpoint is receiving.

The front-end part

We can send data to this endpoint with a fetch or ajax call in javascript.

Example with Fetch

fetch('https://example.com/wp-json/example/v1/action?param1=test&param2=test2')
  .then(response => response.json())
  .then(data => console.log(data));

Example with jQuery ajax’s method.

jQuery.ajax({
    url: ''https://example.com/wp-json/example/v1/action?param1=test&param2=test2',
    method: 'GET'
}, function(data, status){
    console.log(data);
});

This should show us an array containing param1 and param2 in the console.

User authentication using the WordPress REST API

When it’s about user authentication, it’s handy to include the ‘wp-api’ dependency when enqueueing your script;

wp_enqueue_script('your-script', 'path_to_your_script', array('wp-api'));

This gives access to the wpApiSettings variable in javascript, allowing you to access the user nonce:

console.log(wpApiSettings.nonce);

This means we can send the nonce to our REST API endpoint and use that to authenticate the user.

An example of communicating with the REST API with an authenticated user using the WP Nonce with fetch:

fetch('https://example.com/wp-json/example/v1/action?param1=test&param2=test2', {
  method: 'GET',
  headers: {
    'X-WP-Nonce': wpApiSettings.nonce
  }
})
  .then(response => response.json())
  .then(data => console.log(data));

An example of communicating with the REST API with an authenticated user using the WP Nonce with jQuery ajax:

jQuery.ajax({
    url: 'https://example.com/wp-json/example/v1/action?param1=test&param2=test2',
    method: 'GET',
    beforeSend: function (xhr) {
        xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
    }
}, function(data, status){
    console.log(data);
});

That’s it! You can basically go anywhere from here, ex: converting the GET requests to POST requests.

More info on REST endpoints: https://developer.wordpress.org/reference/functions/register_rest_route/

About Marinus Klasen

Marinus has been working in software/web development for more than a decade. Since 2020 his attention shifted on sharing knowledge and developing products and tools for sharing knowledge.

Marinus Klasen on Twitter

This site runs on Cloudways.
It's fast isn't it?
Cloudways offers high-quality, fast and affordable hosting.

Learn more

Need a hand? Post your project and hire me and other top notch developers on Codeable.

Hire me on Codeable

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Ready to take action?

I'm looking forward to discuss your projects and goals!
Feel free to reach out using the contact details below.

Marinus Klasen

[email protected]
twitter.com/marinusklasen
linkedin.com/in/marinusklasen

  • GitHub
  • LinkedIn
  • Twitter

Have you read?

  • Storing private data with SSH on WPEngine sitesDecember 15, 2022
  • Get the HTML content of a block edit page or post in WordPressNovember 30, 2022
  • Rename Coupon code text to Discount code in WoocommerceNovember 3, 2022
  • Background-size cover in mPDFOctober 22, 2022
  • WordPress.com SSH & duplicating a WordPress.com website locallyOctober 11, 2022

Copyright © 2023 · Marinus Klasen | Webdesign by Team Rood