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

add_action('wp_enqueue_scripts',function(){
    wp_localize_script( 'wp-api', 'wpApiSettings', array(
        'root' => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' )
    ) );
    wp_enqueue_script('wp-api');
});

Front-end part

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

</script>
<?php 
});

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(){
    if(!isset($_GET["post_id"]))return;
    $view_count=(int)get_post_meta($_GET["post_id"],'view_count',true)+1;
    update_post_meta($_GET["post_id"],'view_count', $view_count);
    return;
}

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.