Ready to use snippet for WP REST API

WP-REST is great tool to connect 3rd party applications to your website and interact with it.

If you want to use it deeply in your website, you need to go to official website and read its handbook.

but what if you just want to use it for some small task and you don’t want to lose more time on reading docs? Then you might need JS code for frontend, and some backend codes for initialization and processing.

In this article i am giving you ready to use snippet, you just put it to your theme’s functions.php and it works.

Of course you will need to change the codes inside response function. In my example i am giving you an example which counts post_views.

Let’s create simple WordPress rest api custom endpoint. Here we go:

Init part – WordPress rest api example

    wp_localize_script( 'wp-api', 'wpApiSettings', array(
        'root' => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' )
    ) );

Front-end part

if(!is_singular()) return;
var my_api_url='<?php echo home_url('/wp-json/app/v1'); ?>';
    jQuery.ajax( {
            url: my_api_url+"/just_visited",
            method: 'GET',
            beforeSend: function ( xhr ) {
                xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
                pid: <?php global $post; echo '"'.$post->ID.'"';?>,
    } );


Processing function

add_action( 'rest_api_init', function () {
    register_rest_route( 'app/v1', '/just_visited/', array(
      'methods' => 'GET',
      'callback' => 'myprefix_visiteds_processor',
      'permission_callback' => function(){return true;}
    ) );

function myprefix_visiteds_processor(){
    update_post_meta($_GET["post_id"],'view_count', $view_count);

That’s all. Using these 3 blocks does all 3 important steps – init, frontend JS script, and backend processing.

Get more useful WP tricks and snippets by subscribing to my mailclub.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.