WordPress REST API Example
<?php
function tomjn_rest_test() {
return "moomins";
}
add_action( 'rest_api_init', function () {
register_rest_route( 'tomjn/v1', '/test/', array(
'methods' => 'GET',
'callback' => 'tomjn_rest_test'
) );
} );
//Congrats! I now have an endpoint, and you can see it by visiting https://tomjn.com/wp-json/tomjn/v1/test :
// Using the End Point in a Theme
<script>
jQuery.ajax({
url: "<?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?>"
}).done(function( data ) {
jQuery( '#tomsword' ).text( data );
});
</script>