So I'll copy tsc-js, that will be the label we're targeting, that means we are now localizing the script that we're loading in up here, then I set the variable name for the object that will contain all the information we're passing, I'll just call that postdata, and then I can set up an array of items I want to pass forward. And here, I want to pass a couple of things, first off, I'm going to pass the post ID for the current post in case we need to test whether we're in the current post or not. Second, I'll pass the theme URI, in case we want to pull any files from the theme itself.
And finally we'll pass the REST URI. So I'll set all this up in an array, the first item will be, post_id, I'll use the function, get_the_ID, so you get the post ID, next, I'll call in theme_uri, here we'll use get_stylesheet_directory_uri, and finally we'll get the REST_url, that will be the URL to the rest API itself.
For this, there's a WordPress function, just called rest_url, and we can upend content to that, so I'll just say wp/v2/ and then close everything off. Now I can test to make sure this is working by outputting content in the console in my browser. So first, the post ID, var post_id = postdata.post_id second var theme_uri = postdata.theme_uri, and finally var rest_url = postdata.rest_url.
Then I can output all of this in the console log, so I'll say post_id + post_id + space theme_uri + theme_uri and finally rest_url and rest_url. Save this, go back in the browser and reload the page, and now if I go and inspect my code, and look at the console, and here you see post_id: 3541 theme_uri and the uri to the theme, and rest_url, resful.dev/wp-json/wp/v2, ignore this error here, this is an error generated by 2017, and it's irrelevant to what we are doing.
- Using a REST client to communicate with a REST API
- Reviewing available routes, endpoints, and arguments
- Adding custom post types and taxonomies
- Altering the API response
- Using PHP for resiliency
- Passing info using wp_localize_script()
- Setting up a REST API request through AJAX
- Outputting selected post data to the front end
- Formatting post data to match a theme
- Triggering AJAX for an infinite scroll effect
- Using AJAX to load subsequent responses