Last active
October 20, 2022 05:52
-
-
Save yanknudtskov/4e221a4b367727c5275dc66f02ac949f to your computer and use it in GitHub Desktop.
WordPress REST API Example #rest-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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