WordPress REST API reference - markhowellsmead/helpers GitHub Wiki

Links

JavaScript

Following code provides us with data we'll need in JavaScript. The nonce allows WordPress to know who the current user is when we pass our AJAX request.

Provide Javascript with the data it needs. (PHP code.)

wp_localize_script('mhm-rest-comments', 'wpApiSettings', array(
    'root' => esc_url_raw(rest_url()),
    'nonce' => wp_create_nonce('wp_rest'),
    'page' => $post->ID,
));

Discover API root path

WordPress adds a LINK element to the HTML head so that we can find out where the API root URL is on our website. This allows us to know what the current path is, without re-writing our code if this path changes.

(function($, undefined) {
    var $link = $('link[rel="https://api.w.org/"]');
    var api_root = $link.attr('href');
})(jQuery);

Comments

Reference.

Get

Fetch comments from the server via REST API. This function just gets the data and logs the server response to the console.

(function($, undefined) {

    function fetchComments() {
        $.ajax({
            url: api_root + 'wp/v2/comments',
            method: 'get',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
            },
            data: {
                'post': wpApiSettings.page
            }
        }).done(function(response) {

            window.console.log(response);

        });
    }

})(jQuery);

Post

After validating the form and ensuring that the API root is available. The real-world example would contain all of the form fields completed by the user. If these aren't passed, and the user is logged in, then the comment is automatically assigned to the user. The response from the server, if successful, contains stuff like the rendered comment, the new comment ID, the gravatar of the commenting person, and so on.

(function($, undefined) {

    function createComment() {
        $.ajax({
            url: api_root + 'wp/v2/comments',
            method: 'post',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
            },
            data: {
                'content': 'Hello world, this is my comment.',
                'post': wpApiSettings.page
            }
        }).done(function(response){
                console.log(response);
        });
    }

})(jQuery);

Cross-Domain

Allow specific domains (origins). (Reference.)

/**
 * Only from certain origins
 */
add_action( 'rest_api_init', function() {

	remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
	add_filter( 'rest_pre_serve_request', function( $value ) {

		$origin = get_http_origin();
		if ( $origin && in_array( $origin, array(
				//define some origins!
			) ) ) {
			header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
			header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
			header( 'Access-Control-Allow-Credentials: true' );
		}

		return $value;
		
	});
}, 15 );