Add Validation to WordPress JSON REST API's Posts Endpoint

Well, the scenario is that we need to create a post via WP REST API and we also want it to be created only when there is particular post_meta present in the post data.

For achieving this, we are going to take benefit of filter json_pre_insert_post which you can find in insert_post function in wp-content/plugins/json-rest-api/lib/class-wp-json-posts.php file.

So, let's create a plugin.

<?php  
/**
 * @wordpress-plugin
 * Plugin Name:       JSON REST API Post Validation Tutorial
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {  
    die;
}

Now, activate this newly created plugin from wp-admin panel.

What we need this plugin to do is that, it should check for a meta_key is_validation_working in the post data and throw error if not exist. So, lets do it.

//The function tutorial_validate_the_meta will be called just before creating the new post
add_filter('json_pre_insert_post', 'tutorial_validate_the_meta', 10, 3);

function tutorial_validate_the_meta($value, $post, $data) {  
//checking if there is post_meta field present or not
    if (isset($data['post_meta'])) {
//This will return all the values of key 'key'
        $keys = array_column($data['post_meta'], 'key');
        if (in_array('is_validation_working', $keys)) {
            return $value;
        }
    }
    return new WP_Error('Validation Error', "Oh ooo! validation is working");
}

Aaaanndd we are done, simple.

comments powered by Disqus