Skip to content

Instantly share code, notes, and snippets.

@lilumi
Last active July 4, 2019 11:47
Show Gist options
  • Save lilumi/c79b60340c74d9e5f18731e196aa3c6d to your computer and use it in GitHub Desktop.
Save lilumi/c79b60340c74d9e5f18731e196aa3c6d to your computer and use it in GitHub Desktop.
wordpress rest api example
<?php
/**
* Regsiter script
*/
add_action( 'wp_enqueue_scripts', function() {
// Set dependency to wp-api, which has nonce and endpoint root.
wp_enqueue_script( 'api-handler', '/path/to/api-handler.js', [ 'jquery', 'wp-api' ], '1.0', true );
} );
// Below is the content of api-handler.js
?>
<script>
(function($){
$('.button').click(function(){
var $button = $(this);
// e.g. Add loading classs
$button.addClass('loading');
// Endpoint from wpApiSetting variable passed from wp-api.
var endpoint = wpApiSettings.root + 'wp-json/wp/v2/users';
$.ajax({
url: endpoint,
method: 'POST', // POST means "add friend" for example.
beforeSend: function(xhr){
// Set nonce here
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
// Build post data.
// If method is "delete", data should be passed as query params.
data: {
foo: 'var',
hoge: 'fuga'
}
}).done(function(response){
// Do something.
}).fail(function(response){
// Show error message
alert( response.responseJSON.message );
}).always(function(){
// e.g. Remove 'loading' class.
$button.removeClass('loading');
});
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment