Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Last active October 20, 2022 05:52
Show Gist options
  • Save yanknudtskov/4e221a4b367727c5275dc66f02ac949f to your computer and use it in GitHub Desktop.
Save yanknudtskov/4e221a4b367727c5275dc66f02ac949f to your computer and use it in GitHub Desktop.
WordPress REST API Example #rest-api
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment