 All right, welcome everybody. Hope you have had or are having a good Thursday. While we get started, I just wanted to mention that I'm experimenting with my microphone setup. So if you can't hear me, please do let me know. I've just kind of moved it around slightly so that I can see my keyboard better. So while you're joining, if you would like to code along with me today, please do get your local environment ready. And there is a link, the plugin that you can download, which I'm going to share the link to in the chat. And you're welcome to download that now or you can download it a little bit later. Hey Thalma, welcome. Thalram. No, not a problem, not a problem at all. Excellent, okay. Eagle says you can hear me. Adrienne says she can hear me. Excellent, thank you so much. Then if you are coding along with me, make sure you download the plugin. If you aren't coding along with me while I do my introductions, please let us know where you're from, where you're joining us from, whether it's good morning, good evening, or good night. So my name is Jonathan. I am from Cape Town in South Africa. I am a ex-developer turned code instructor, which means I've run these workshops and I create tutorials and I do various. I discovered, I realized recently I'm actually a content creator now, which I never thought I would refer to myself as. So that was an interesting little discovery. I'm currently employed at Automatic as a sponsor contributor to the training team. So it's the team that creates all of these online workshops and tutorials and lesson plans and courses. And if you want to find me on Twitter, you can find me at John underscore bossager. Twitter also has my Tumblr URL and my mastodon instance URL and all those social media things that I'm terrible at. But mostly Twitter is where I converse around developer-y focus things or on my blog, which is also linked in my Twitter account. Awesome. So today we are going to be looking at using the WordPress REST API. Originally I had planned to run a session today on extending the REST API, but then I realized before we can extend something we need to understand how to use something. So I'm probably gonna get a few sessions out of this. We're gonna be looking at how to use the basics of how to use it. We're going to be looking at the basics of how to do authenticated requests to create data in your WordPress site, how to extend it for custom post types or for custom functionality. But today we're just gonna be looking at how the basics of the WordPress REST API, what it is and how we can use it. A few announcements before we get started, as I always do. First of all, welcome and thank you to Thelma who's co-hosting with us today. Thelma is my superwoman. She flies into the last minute and saves me by helping me co-host these sessions. So again, thank you Thelma for joining us. Thelma is a pleasure. Cool. As always we are presenting in focus mode, but please do feel free to enable your video if you would like to. You are welcome to ask questions as we go along. You're welcome to ask questions in the chat or if you would like to do it verbally you can unmute and ask questions that way. The only thing that I do ask is if your question is not specifically related to something that I'm presenting at the time, then please keep it for one of the pauses that I do allow for and set aside for. Cool, a few more announcements. If you want to just go along as I mentioned earlier, please make sure your local install is ready. Make sure you've downloaded the plugin and you have it installed and active. As always, if I start rushing off and going too fast, please do slow me down. I will be posting the session to WordPress TV afterwards and I will post the link in the meetup.com comments. I usually do it on the Friday afterwards because I have to download the file uploaded to be transcribed and then upload all of those to WordPress TV. And then finally, if you haven't been there already and you're looking for more WordPress-focused educational content, please do consider visiting learn.wordpress.org. Okay, those are the announcements. Let's move on to the learning outcome. So today, we're going to be looking at how we can use the WordPress REST API or I'm gonna just be referring it to as the WP REST API for the rest of today. I really hope my battery loss, let's hope it does. We're gonna be learning about roots and endpoints in the REST API and how they work. We're going to be learning how to use global parameters and the examples we're gonna be looking at is how to limit fields in the responses and how to implement pagination and ordering. Then we'll just do a very brief overview of authentication with the REST API. We won't cover that today. I'm planning a separate session on authentication because of how the authentication works with the REST API. And then we're gonna look at a practical example of how we can use the REST API in plugin and why I believe at least it's better to use the REST API versus something like Admin Ajax. Our objectives for today, we're going to set up and review the example plugin in a minute and just go through what it all does. Then we're gonna learn about what these terms mean. So what does REST mean and what does an API and what does that mean? We're gonna make sure we understand the difference between an endpoint and a root in a REST API. We're gonna learn how to alter the response data a little bit. And then we're actually going to go and update the example plugin code. And I'm gonna show you what an Ajax-type example would look like, which is something you may have seen before. You may have implemented in your plugins before. And then we're going to look at how we would do it in a REST API. Okay. Derek says, thank you for sharing your power words. I don't know if I'm happy about them, but it is what it is. Okay. So let's have a look at the plugin itself. So I've got the plugin installed on my site already. So here it is over here, the WP Learn REST API plugin. And very simply, it just creates an admin page. If you happen to have, if you attended the security workshop I ran a while back, if you happen to have that plugin installed, you might find that that plugin and the REST API plugin may conflict with each other. So you might need to disable that plugin. And that's just because some of the prefixes are the set. So if you do get any conflicts when you install this plugin and you have that security one from last week, you can still just disable that for now. It just has three buttons across the top. It has a load post by admin Ajax button. It has a load post by REST button and a clear post button. Currently, the load post by REST does nothing because we want to actually write that code in a second. But if you click on the load post by admin Ajax, it should then load the titles of any posts you have in your test site in the text area. Currently, I just have the one post. So I'm very quickly going to install the FakerPress plugin to generate some posts for me. So if you would like to do this, you're welcome to join me as well. If we click click on plugins and we click on add new. And then in the search box, you can type in the word FakerPress. This is a plugin that I use quite a lot just to generate random data for a local WordPress install. I'm going to install that plugin. And then once it's installed, we can use it to generate some random posts. Okay. While we're doing that, while it's being installed, let's have a look at the plugin code itself so that we can see what that's doing. And I'm not getting my code window to come up. So I'll do it this way. So if I open up my local WordPress site, it's in my development web, no, not developed, sorry, local environment sites WordPress directory. And inside of there, let me just close these down. Inside of the plugin directory, here is the learn REST API plugin. It's very simply two files. It's a PHP file to handle the core plugin functionality. And it's a REST API.js file to handle the Ajax processing and currently the clear button. And sorry, this is the wrong site. I'm looking at the wrong site. I do apologize. That's not the folder that I want. I want the other site that I actually use for these sessions. So it's sites learn press. So if you're wondering, I use WordPress for development and learn press for these sessions. And I opened up the wrong site, which is why I get confused. Okay, let's go back to plugins, learners API, there it is. Okay. So if we have a look at this plugin code, it's doing four main things. It's setting up the admin menu and that uses the admin menu action. It has a callback or learn REST sub menu and then that uses the add menu page to set up the menu page. And that's basically setting up, let's find the WordPress dashboard that's setting up this link in the dashboard there. Then there is the render admin page function, which is basically rendering the content inside of that page. And all that's doing is it's a very simple div class with a header, the three buttons across the top, another header, H2 header, and then the text area. So it's very simple and straightforward HTML, nothing special there at all. Then we have the NQing of the JavaScript file. So this is the WP Learn REST API.js file. And if you've NQ JavaScript files and plugins on themes, this will be very, very familiar to you. You use the register script function to register the script. You give it a handle, you give it the path to the file. You might set a dependency. So for example, if you're using jQuery in your plugin, you might need to specify that jQuery is a dependency. And what this does is it tells WordPress to load your plugin code after jQuery is loaded. Then you can pass in a version, which for the purposes of this plugin, I'm using the time function in PHP. So every time the page refreshes, it'll generate a new time output. It'll basically be the second since epoch time, which basically updates the version number. So it's a thing called cache busting. It prevents the browser from caching the JavaScript. And it's a very cool way when you're developing of making sure that you're not getting old JavaScript if you've made changes in the file. And then you NQ that script file. So you NQ it into the process of WordPress setting up JavaScript files. And then at the bottom, we're localizing the script. And what localizing does is it creates an object, in this case, wp underscore learn Ajax with an Ajax URL key and the value of the Ajax URL path. So if you've implemented Ajax admin Ajax before, this will be familiar to you. It's basically you need to tell WordPress where the Ajax endpoint is that I need to send my request to so that when it processes the Ajax request, it knows what file to hit. And then the other part of an Ajax request is you need to set up a function hooked into an action that has the prefix wp underscore Ajax underscore and then whatever name you want. And this part of the hook you actually use in your Ajax request in the JavaScript side, I'll show you that in a second. And what WordPress does is when the Ajax request happens it picks up the action and then goes and looks, creates a hook to fire and then fires your callback function, which is the, in this case, wp underscore learn underscore Ajax underscore fetch underscore posts. Description function names are great when you're coding but not so great when you're presenting them and you have to read them out. But all that function is doing is it's using the internal get posts API function which is gonna return all of my posts and then it returns the post as a JSON object. So it uses this wp send JSON, takes the array or object converts it into JavaScript object notation and sends that back to the request. And then all Ajax handlers must also die because if, and I don't like dying in PHP it's a term that they use, I prefer using exit but WordPress has one called wp die because PHP has one called die from back in the day. But basically it prevents any further execution of that file because there might be something hooked in somewhere else and you don't want that to be firing when you're running Ajax. Then in the JavaScript file, right at the top we've got the jQuery document ready opening thing here which is basically says when jQuery is loaded then process all of this code. And basically what this is doing is it's getting the load posts button based on its ID which is, this is how you do it in jQuery. And then it checks if the load post button is not undefined or it's not null in other words, it's a physical button on the page. And this is a good way to make sure that all of this code doesn't run everywhere else. It just runs when that button is available. There are other ways to do that but I'm just doing this one here for the purposes of today. On the on click event of this load post button which is the learn Ajax one. It will then create a new function which is a post request, the jQuery post Ajax request which requires the Ajax URL. So we get it from the learn Ajax object which we set up over here and there's the Ajax URL and we get the Ajax URL there. We need to pass at the action which is the learn underscore fetch posts which as I remember, if you remember I mentioned is part of the action name there. So that's how that all ties up. And then when this is done it returns the posts to a done function and then this goes through gets the text area based on the ID, loops through the posts and appends just the title to the text area. And if you've never seen Ajax before in WordPress and you find the way this is all implement to be very confusing, don't worry because I've been working with this for a number of years and I still forget a lot of this because it is very kind of clunky to have to remember to set up the Ajax URL and set up the action and all those kinds of things. And that's one of the things that I love about the REST APIs, I don't have to do those things. So that's why I'm a big fan of what we're doing today. Okay, so any questions on all of this code we've just looked at, you're welcome to open it up on your side as well and have a look through anything you're not sure of. While I grab a quick sip of coffee, actually water today, I don't have coffee and then we will continue on from there. Right, so let's talk about the REST API. So if you've never seen it before there's a website called developer.wordpress.org and it's basically all of the developer resources you might be most of my workshops are based on documentation. In fact, all of my workshops are based on documentation from this website. And there's an entire section of the developer resources page dedicated to the REST API. So I'm just going to copy this link into the chat very quickly. And if you load that up in a browser and scroll down there's a section at the bottom of the REST API and you click there on make applications and it takes you through to the REST API page and it starts talking about what the REST API is. So if you don't want to sit through this workshop you're welcome to go and do some reading but we're going to cover some of these ideas today. But basically a REST API provides an interface for applications to interact with your WordPress site by sending and receiving JSON or JavaScript object notation objects. And one of the most popular, maybe not the best word for some folks but one of the things that is using the REST API quite extensively is the WordPress block editor. Now the REST API was merged into WordPress core and I think it was 2016. It was originally developed by one of the senior developers I think he's now the CTO of a company called Human Made. And the reason that the REST API was originally developed is because there was no formalized standardized way for other web applications or mobile applications or any third party applications to interact with WordPress data. So you might have a situation where somebody has a WordPress site like a news site and they want to build a mobile application but they want to be able to talk directly to the WordPress site and get the data from the WordPress site to show it in the mobile application. And around the web, REST APIs have become these sort of standardized formalized way that folks do this. So let's talk about the words API and about the words REST so we understand what they mean. So here it is an API is an application programming interface. Now all that means is it's a way for one piece of software to talk to another piece of software. WordPress itself has a number of APIs and we have actually in the code in this plugin we've actually used some of these APIs. So in using the add menu page function we've interacted with the menu API which is the application for programming interface for creating menus. In, where's the other one I wanted to get? In using the get posts function we've interacted with the data API for getting data to and from the database. These just happen to be wrapper functions around deeper things within WordPress but they're part of those APIs as application programming interfaces. Most folks when they see the word API they default to think while REST is the only version of an API but an API is any way of talking between two pieces of software. Here it also says that REST stands for representational state transfer and then it talks about a set of concepts for modeling and accessing your application's data as interrelated objects and collections and that's a lot of big words. Basically what REST is is formalized. So with a REST API there are a specific series of what we call routes. So for example, and I'll show you these in a second and we'll test some of these ourselves in a second in WordPress there is a route to get posts. There is a posts route. And if you send what's known as a get request to a post route you'll get and it'll return a bunch of posts. If you send what is called a post request to the posts route two different things same word but two different things I'll expand the difference in a second and you pass it some additional data like the post title and the post description and maybe some metadata it'll then create a post. If you send a delete request to the posts route it'll delete a post. So you're using the same route every time but depending on the HTTP verb or HTTP method being sent the route will perform a different thing. So let me show you kind of what I'm talking about here. This is my local WordPress install learn.wordpress.test and I'm gonna copy this arch and you're welcome to do this along with me. If you take your local WordPress install URL you open up a new browser and you go to wp-json and you hit enter. And it's gonna give you a whole bunch of text. Now in my browser window I've got a Chrome extension installed called JavaScript PrettyPrint or something like that. Let me just search it quickly for you. Not JavaScript, sorry, JSON PrettyPrint. And this is an extension you can... No, that's not what I'm looking for. Extension maybe. JSON formatted, that's the one, sorry. And so this is an extension you can install on Chrome-based browsers and it'll take your raw JSON and then pass it into an easier to read way. So some of you might be seeing something like this right now it's just all looks like a whole bunch of text. If you have that extension enabled and you can hit on the pass button over there then it shows you in an easier to read format. Now if I hit F12 to open up my developer tools and I'm gonna just close this and try and move this thing out the way because it's getting in my way right now and you have a look at the network tab and you refresh this URL. You will see there's the initial request there if I click on WPJSON. And there it says request URL is learn WordPress test WPJSON. And right below the request method is it's a get method. So every time a request happens on the internet whether you're using a browser whether it's an application making a request whether it's a mobile application making a request it will have a method. By default that method is usually get me some data. So I send a request to this URL and I say to get me some data. But you can also pass a post request. Post request you will typically see when you're submitting a form. Then there's fields to fill in, there's a submit button. When that submit button fires it'll go to a request URL but it'll be a post request and it'll send some data with the post. And then the other options you have are delete to delete something. And then there's also an update to request option method as well. But by default most things are using get. Okay. So then if we look at how these things work there are two key concepts I wanna dive into before we stop for questions. The first key concept is what is a root and what is an endpoint? A root is very simple, the URL. So you'll see it talks here about if we make a get request to this URL we are returned the response. And that's the one we just did. Now the other one you can look at if you go back to this option here and if you look underneath here on my screen you'll see there's namespaces and there's this WP slash version two. So I'm gonna update here to WP slash V2 and then I'm gonna append posts. And that's going to do again the get request. There's the URL. It's again doing a get request and that get request tells WordPress somebody is requesting the posts because of the end point or the root should I say. So that's what makes this a specific endpoint. So this is the get endpoint to the posts route. If I wanted to create a post I could submit a request to the same post URL but change my request method to a post request method and then pass in the post title the post description, the post option. WordPress would then know, ah, this is a post not a get. Let me take the data that I'm expecting and let me create a post out of this and then it will return probably the post response. So when we talk about roots we're talking specifically about just the URL. When we're talking about end points we're talking about the method that is passed to the same URL. So there is the get endpoint. There is the post endpoint or there is the delete endpoint typically you would use. Today we're gonna be focusing mainly on get endpoints for whatever URLs we use. We're gonna be specifically working with the post route but it's a good idea to understand what these concepts mean and how they work with the REST API. Okay, any questions on roots, endpoints, REST API or how that all fits together before we go on? Okay, we don't seem to have any questions. I've already covered the first three items in my list which is great. So now we want to learn how to alter the response data. So WordPress gives you, let's go back to the code here. WordPress, the documentation has this great section called using the REST API. And as you can see there are various things we can look at various things we can learn about. There isn't enough time to cover all of them. So I'm just gonna cover a few common ones that you might want to look at using. The first one is under global parameters and it's the fields parameter. So it's the first one in the list. And basically you can, as you can, if you look at my, let me close down my developer tools. If you have a look at my post request right here, you'll see, let me make it a little bit bigger so that it's a little bit more readable. You'll see that I've got a bunch of posts on the screen with a bunch of fields. So I've got the ID, the date, the modified, the modified GMT, the slug, the status, the type, the link, the title, the content, blah, blah, blah, blah. Now, for the purposes of my plugin, and let's go back to my page, I might only want, or in this case, I might only want the title. So when the response comes back, if I can somehow limit that response to only send back, for example, the title, that would be good but make the request faster. If you think about when you make requests, you want the PHP to process as quickly as possible. And if you make the query to the database and you say, return all the fields, and then only on the JavaScript side, you say just up with the title, then the query has to get all that data, gather it all into an array which takes up memory, and then split that up to the response JSON, and then you take that JSON and you filter it. Wouldn't it be great if you could say to the query, no, no, hang on, just get the title for me, or maybe just get the ID and the title and the date. The query would be faster, your PHP would be quicker to get the response, your response would be smaller, and everything would be quicker. So the fields global parameter is one that I've used quite a lot in my development. And the way it works is the same as any kind of query string that you may have seen on the internet. So any URL on a website can accept what's known as a query string. A query string starts with a question mark. So that indicates that this is the query. And then it has usually a field, which happens to be fields in this case, so bad choice of words, but it has a field and a value. And the field and the value are usually separated by an equal sign. So the field might be name or title, or in this case, underscore fields or whatever, and then the value comes after that. If the value needs to be more than one, it is generally delimited by a comma. And if you want to do more than one field in your query string, you would delimit that by a question, I'm sorry, by an ampersand. And I'll show you how we do that later. But for now, we're just gonna start the fields parameter. So if I copy this out over here, and you're welcome to do this with me if you would like, and I append this to the end of my post route, like that. And let's say I just want, in my case, I just want the ID and I just want the title. So there we go. So the fields parameters being passed, and I just wanna return the ID and the title. If I now hit refresh, which will generate another get request in this end route, but it'll pass in those fields, there I get just the ID and the title coming back. Okay. Now I've still only got one post on my site, so I wanna make some more posts while I think about it. So let me quickly jump over to my FakerPress plugin that I installed earlier. No, not users plugins. And I'm going to just activate that very quickly. And I'm going to go into FakerPress and go into the posts option. And I'm gonna say I want to generate 10 posts and I want them to be the last 15 days. So I always wanna make it from today and going backwards, because otherwise, if I make them going forward, they're sitting draft mode. I'll leave them as posts. I'm going to disallow comments. I'm going to reduce the randomized HTML. I'm gonna take out all of these because adding all of these randomized HTML elements takes longer. So I'm just gonna do something like that. I don't need images because this is just for my purposes. I don't need that or that. Okay. And then I'm just gonna hit Generate. And that's fake to a bunch of posts from you, which is perfect. So if I go back to my post list now, there they are, they're all there. Okay. You're welcome to do that now as well if you would like to. I'm gonna take a break. I see there's a question. So if you've got FakerPress and you wanna generate some posts while I'm asking the question, you're welcome to go ahead. So Shelly says, so in the case of a WooCommerce installation, you could get additional fields like price. So yes, you should be able to. I haven't worked with the WooCommerce REST API in a while, but theoretically price should be available there. Any, I'm pretty sure that WooCommerce does have a full REST API implementation. Depending on where the price is stored, I think the price is stored as post meta. So you might need to add some global parameters to include the post meta on the post. I can't, it's not in my head exactly right now, but I do plan on doing that in a future session. So if you don't find the answers to that, when we get to how to include more data and how to extend in those things, we can cover it. But theoretically, it should be possible to get additional fields like price from a REST API endpoint. If it isn't, if it's not possible, that's a good one to raise with the developers and say, hey, would it be cool to add this to your REST API endpoint? Okay, so we, it's global parameters. So we specified ID and title and it returned the ID and title. If we wanted to add, for example, the author, we could add the author and it returns the author, or the author ID in this case. So there's a whole bunch of fields that you can use. You'll also see at the bottom that you can provide the same list as using query parameters to erase syntax instead of comma separated. So you can say fields and then you can pass in an array and you can say author and fields ID and fields accepts. There's two ways that you can manage it. I personally prefer the comma delimited way, but the great thing about software is it's always more than one way to do things. Okay, so that's how you can filter the data that you return. The other kind of things you can do, you can do pagination. So let's go back to the original response here and you'll see that by default, I'm getting one, two, three, four, five, six, seven, eight, nine, 10 results in my response. If you're wondering where that 10 comes from, it's based on your settings, your WordPress settings, and I can never remember where these are, but I think it's in reading. There we go. The blog page is sure at most 10 posts. So that's a default WordPress setting. So let's see if it is that one. I can't remember. Let's just save that, make that 15, and then let's do a response here. The last one was one, one, nine. Okay, it's not using that one. It's using another setting somewhere. It's probably a default REST API thing. So what we can do there is we can say, here we go. We can specify the per page setting. So we can specify the number of records to returning one request specified as an integer for one to zero. So let's add per page to that. So we still want the fields, we saw the title, author, et cetera. Now we're gonna add a query parameter. So we use the ampersand and we say per page equals, and let's call it 15. And so now we've got one, two, three, four, five, six, seven, eight, nine, 10, 11. Okay, so I've got 11 posts. If I wanted more, I could add more, but at least it's working. It's getting me the total amount is there. We can change this to five if we wanted to. So there we go. I've got one, two, three, four, five. I can't scroll down. And what you can also do is you can say, show me page two. So we know there are 11 posts in our site. I'm wanting to see five per page, but I want to see page two now. So you can use the page parameter. So the first page is obviously the first one. So that defaults to one. So let's go for page two. So again, we can just go ampersand, we can say page, page two, and it gives us the second page. And so you can go on and on and on. So if you're building a mobile application, that's great. Because often you won't want to load, let's say you've got a hundred posts in your news app, a thousand posts, a million posts, whatever it is. You only want to load a certain number of posts that you use to begin with. And as they scroll, then you might want to make additional requests to load those posts or whatever the case may be. Shilis is mine. Yes. Oh yeah. I was just going to say there's a follow up to the question. Yes, yes. Shilis says, thank you. My interest in particular is with custom post types using ACF. So I will be honest with you. I don't use ACF. I use custom post types hard coded myself. So I can't speak about ACF. However, I used to work for the company before I joined it was Matic that acquired ACF. So I used to work for delicious brains. So what I can suggest is to reach out to them and see if the ACF fields are available. They should be available as post meta in the REST API requests. But I unfortunately, I don't know the ins and outs of ACF myself. Okay, so I'm sorry that I can't answer you there. But I do know the folks at ACF, they're a great bunch of people. So if you reach out to them and check with them, that should be possible. Okay, so where were we? Okay. All right. The other thing that you can do is you can order your results. So you can say I want them to be ordered ascending or descending order. You can say you want to order by a specific field. So for example, let's say, let's take this example that we were looking at and let's just take the title to show what's happening. So I'm gonna update my fields to just show the title and I'm gonna stick with per page five and I'm gonna go back to page one. And then I want to order and I want to order by the title, for example. So let's go order by title and you'll see now it's ordering by title descending. So it's starting with V and then T and R and R and Q. So it's going in reverse alphabetical order. If I wanted to change that order, then I can use the order parameter and I can say ascending or descending. So it's descending by default. But if I want to change that, I can say order equals ascending and hit refresh. And now it is the other way around starting with A and going down. So there's multiple different things that you can do. And if you go, Paul, thank you for answering that question. As I say, I can't speak of ACF. I'm glad there are folks here who know ACF works. Paul says there's a setting in ACF to show fields in the REST API. So there you go. That's awesome. So thank you for that, Paul. Cool. My Zoom toolbar has gotten wonky. So I've just moved it very quickly. Any questions on any of these global parameters we're looking at? There's a whole series of documentation on this. So I do recommend reading it. There are more than just the global parameters I've covered today. There is a embed global parameter. There's a method. You can override the method being sent. There's an envelope for various things. But the ones that I use the most are the fields to limit the number of fields coming back. The pagination to limit the amount of results in the response, and then the ordering is those are the ones that I tend to use the most. OK. Any other questions on how to alter the REST response data based on those fields before we start having a look at updating our plugin code, which is the fun part? OK. Cool. There don't seem to be any questions around everything we've covered so far. So let's move on to why I recommend using the REST API. So the first thing I've already mentioned, and that is that I find using Admin Ajax to be a lot to remember. Number one, you have to remember to pass in the Ajax URL. Number two, you have to remember to set up your Ajax handler, your function which will trigger the Ajax response and also the Ajax request and then get the code that you need. And you have to think about filtering which fields you need. You have to think about pagination in your response and all those kinds of things. On the code side of things, you need to, if you're comfortable with using something like Axios or the documents Fetch, the browsers Fetch functionality in modern JavaScript, you can use that. But if you come from the old Ajax days, you're probably using jQuery. So then you have to remember how jQuery works. You have to remember to set up the request. You have to remember to pass in the action. The one thing that I'm not even doing in this code is we're not doing any kind of non-checking to make sure that the request, and you remember in the plug-in workshop we did last week, we mentioned about using and we have to implement non-sys and then check the referral. We have to do all of that. So there's a lot going on that you have to remember. The cool thing about the REST API, I'm going to go back to the documentation here, is along with the REST API being included in core, there is also a backbone JavaScript client. Now backbone is a JavaScript framework, similar to jQuery, but specifically for, I've just sent a message to somebody privately. So apologies for sending a private message. I need to send this to everyone. Zoom does this weird thing where, there we go. Okay, apologies Derek for sending you that direct message there in the same URL. But backbone basically is a way of modeling your data. And so the person who developed the REST API and the core contributors who merged this into WordPress, they made sure that there was a built-in JavaScript way to access this data. And you'll notice that to activate the WP API plug-in, you can just either enqueue the script directly like this, or if you're using your own JavaScript, you can just update your dependency. So instead of being required on jQuery, you can update it to WP API. So that's what we can do today. So the first thing we're going to do is that. We're going to update our REST API part. We're going to jump into the plug-in and we're going to go down to the enqueue admins scripts section where there's the learn REST enqueue script function. And I'm going to update the dependency array. And I'm just going to update that to WP API. That's the first thing I'm going to do. I'm not planning on using jQuery anymore. So that's the first change I'm going to make. Then because I'm not using Ajax, this entire section of code here can just come out. And if you're like me, you like deleting code. I'm not going to delete it today. I'm going to comment it out just for the sake of what we're doing. But we don't need this localization of the object anymore when parsing in Ajax URL. So that code can come out. We also don't need the handler because we're going to be doing everything using the REST API and the backbone JS plant. So already our entire, let me just check here. Yes, our entire PHP section of code has now almost halved, which I think is great. It's always good to delete code you don't need, my opinion anyway. So because we don't need to worry about Ajax, we don't need to worry about necessarily using jQuery. We can just delete all this code. Cool. Then if you are using jQuery for other things, 100% fine, keep using jQuery. But just to access the REST API, you don't need jQuery. You don't need the jQuery post method. So again, all of this code can come out. So I'm going to comment out all of this code. And then all we need now is some way to access the data. So let's have a look at the documentation and see what the documentation tells us. So if we scroll down and it says here, the library parses the root endpoint, the schema, and creates matching backbone models and collections. So when we talk about the root endpoint, we're talking about this one, which then tells us what the other routes are. So there's posts and uses and various other things. Okay. So the model and collections for WordPress include all the data we're used to, categories, comments, media pages, page revisions, posts, and all of those things. And then we can create collections of those things. So we can create a collection of comments we can create a collection of, for example, posts to then use it in our code. So if we scroll down, we can see some example codes. So let's have a look. We can also do different methods. We can pass get, put, post, patch, and delete. We've spoken about that for a second. And we can pass in various options. We can pass in filtering. We can pass in page, per page, order by all these things we're used to. So let's have a look at how this could work. So if we scroll right down here, there's a model example that talks about how to fetch posts. And if we scroll down a little bit, sorry, collection example. Sorry, that's what we're gonna use today. Here we go. So it's here under collection examples. I'm going to pop this in the chat. And it's simply a case of creating a new post collection as a WP API collections post method. Now, if you remember, if you attended any of the developing blocks with plain JavaScript, you remember, there was this global WordPress object or WP object that we used to import the block edits or related things. The API is also on that object. So that object is always there and we can just use it. Because it's there, we don't have to worry about importing, we don't have to worry about dependencies or anything like that. Because we have told our plugin code to rely on the WP API dependency, when our code runs, that API is available. So the first thing we can do is we can grab this code as it is here and we can pop it in our code window in our JavaScript. Okay. So let me start that. So that's gonna create a post collection, number one. And then it's gonna fetch that collection of posts. Now, I want this to happen on the button click. I don't want it to just happen randomly. I want it to wait for a button click. So you'll see just below that, I've already got this clear post button code, which is doing this similar thing to what we're doing in jQuery. So it's getting the button by its element ID or getting the element by its ID. And then it's running the checks if it's not defined and if it's not null, then it does something. So that's kind of what we wanna use. So we can copy this code and then just make some changes. And I'm gonna run you through what this code is doing and what we're talking about in a second, but let me just get to this point. Okay, post collection fixed. Okay, this is giving us an error because we're not wanting to work with clear posts. We're wanting to work with rest API button. So this is the button's ID over here. This is in the PHP file currently on line 31 on my screen. WP-learn-rest-API button. So let's grab that and pop it in there. So that's the ID. It's gonna get that button by the ID. We need to change this variable because this is going to cause a conflict. So we'll call this the get posts by rest button. Did that way, a little bit easier to read. And then we can just copy this for the checks. So if the button is not undefined and if it's not null. And then we say, great, get the post collection and fetch the posts. Now I'm getting an error here. So let me see why that's happening. I think it's because there, that's why. Okay, there we go. So that should create the new collection, fetch the collection. How do we see the collection? Well, let's try something. Let's console log the post collection and see what we get in there. Okay, so let's go back to our browser and let's refresh that admin page. And then we can open up developer tools, switch to the console. And it says your WP API collections post is not a constructor. So it's giving us an error. Something's gone wrong somewhere. So let's have a look here. I think I might have copied this out of the documentation incorrectly. And it looks right. Let me have a look at my final code just to make sure that I haven't done something wrong. It's fetch, it should just work. Okay, well, let's see what happens when we refresh that. Oh, there we go. I hadn't finished it correctly. So you'll see that it's running that code already. So it says if the button exists, then run the code. Now that's not ideal because I only wanted to run when the button clicks but let's have a look at what's in that post collection first. So here we have the post collection and you can see that it is an array and it has, sorry, it has a zero length there. We look at models, there's an array of models and here are all our posts. So the attributes there, it has an author, it has categories, it has the content. So it's getting all of that data from the REST API in literally those two lines of code, which I think compared to admin Ajax is very, very cool. But now we don't want all of that data. We just want to filter by, for example, the title because we just want the title and the thing. So let's have a look at how we would change that. So getting back to the documentation, here we can talk about getting the last 25 posts or we can do this filtering. So we can say filter, order by title and various other things. So let's do this, let's grab this code and go back to where was it? It's in the fetch. So let's have a look at what that looks like. So fetch data filter and what we should be able to do here is we should be able to do fields and just specify title. I actually haven't tested this. This is me trying something new, but let's see what happens. Data filter fields title and let's see what that does. So if we refresh, have a look at that. Models, attributes. Okay, I haven't done the right, I think it might be post title. Let's have a look here. What I'm going to do is I'm going to have a look at the actual end points, posts. You know what I might actually have to do it the way I did it in, so filter fields. Underscore, I think that's what I've done now. Let's try that. No, it's not that. I can't remember what it is now, but there is a way to filter it by the fields. There is a way to do the ordering, the page, the per page and all that kind of thing. So now the last thing we want to do is we want to make sure this happens on the button click and on the clear post button, I'm doing the same thing. I'm adding an event listener on the click and then running that function. So we can do exactly the same thing over here. We can say on the event click, then run our code. So let us grab this at the bottom here and pop that in. And then we can do all of this. So that'll get the post collection. I'm going to take out the filtering for now. Do the fetch for now. And then we want to do something with this code. We want to take it and we want to add it to the text area. So there is a thing that you can do using the backbone client. Let me go back there for a second. Collection examples, no, it's what I want. Fetch. And then there is a done. Here we go. So you can do a done function and you can return the posts. So let me show you what that looks like. So after your fetch, you can specify when it's done. And that's a function that will then receive the posts and let's console log the posts there. So we see what that looks like. Okay, so post collection, fetch, return the posts and then console log them. So let's have a look. So now we shouldn't see anything in, can I access clear post button? Okay, I've done something wrong because I've done, I want the rest post button. Sorry about that folks. So it's the get post by rest button, adding the event listener will then trigger the right button. Okay, there we go. So let's go back here. Let's have a look at this. There we go. So now it's not loading in the console because nothing's happening. But if we click the button, then things happen. Then it does the rest request and there it gets the posts. Okay. Is anybody needing me to pause there to catch up if you're coding along? Okay, let me pause there for a second so you can see what's going on. Are there any questions around anything we've done so far? I can run through this code if we need to again. So let me spread this out a little bit so we can see and I'll add some comments so you can see what's going on. So this line is just creating the rest, the post by rest button variable based on the ID of the button. The next line is checking if it's not undefined and it's not null. The next line is adding the click eventlessness. So it's basically saying, get ready for when this button is clicked and then do something. And that's the opening function there. Then it creates the new post collection using this WP API collections post method. And then it fetches the post. So the creates in the collection doesn't actually get the data. It just prepares it to get the data. And this is basically the post model. So it says, the next time I call a fetch, it's going to be getting posts specifically. Then when it runs the fetch, it gets the actual data. And this done function, it's a thing in JavaScript called the JavaScript promise. So when it runs, it's got to go off and get the data and then come back and return the data back. So it says, I'll wait for you to finish. And when you're done, return it to this new function and pass it into this post variable. And then I can log those posts. Okay. Is everybody up to speed with me there so far? Any other questions? Anybody need me to slow down? Okay. So the last thing we're going to need to do is actually add this to the text area. So the way we did it in JQuery was we created the text area element as a variable based on the ID. Then we use the for each method to loop through each post and then we append it. We can do exactly the same thing with our REST API. So if we copy this code from the Ajax part and pop that inside of this return function here. So we can say, get the text area. The one thing we'll need to change instead of using the dollar thing for JQuery, we change it to document get element by ID. Okay. And we don't have to pass in the hash because it'll just look for that ID. But then we can just loop through the posts and we can do the same text area append and passing it the post title. So that can stay exactly the same. That's the one thing that does stay the same between the two. And if we now run that code, I'm going to close this up a little bit. Now we should see that it loads the rest, the posts, should I say via REST. Okay. It's giving me undefined. I've probably coded something wrong some way. So let's have a look at a single post. So let's console log a post here. Sorry, what am I doing? Console log the post. Thank you. And it's refresh. Okay. So the post, oh, sorry. It's post, post title, I think it is. No, this title post, post title should work. Oh, it's post title. I've got post. Okay. So do you see what happened there? I was using post underscore title, which the get post PHP function will return from the database. The REST API response just has the word title. So that's the one small change we need to make. Instead of calling post title, instead of calling post.post title, we call post.title because that's the field in the REST API response. So now if we update this and reload, now we're getting a bunch of objects. Oh, that's why. That's the other thing. I always forget this part. So in the REST API, the title is always rendered. And the reason that happens is because there is a hook that hooks into the get post title function that allows someone to alter it during the course of front-end rendering. And that's if there's special things or functionality, whatever. So all you have to do there is append the dot rendered string to your post title. So it's post.title.rendered. And this is the one difference between using the REST API and using admin Ajax. You're just gonna get post title coming back if you use get posts. With the REST API, it's gonna be post.title.rendered. But if we refresh that now and reload, we get a lot of post titles. Okay. So the two reasons I prefer using the REST API to using Ajax, well, three reasons. Number one, it's a lot less complicated. This looks complicated now if it's the first time you're seeing it. But if you look at the amount of things that you have to remember, you just have to remember specifically for getting the data. The REST of this is all really just JavaScript related things, checking that the button is there and those kind of things. But the actual part that's important is this part, getting the data. And it's really just creating the collection and then fetching the data for that collection. And then once it's done, doing something with it. In our case, we just happen to be outputting it. But that's a lot less to have to remember than remembering that you have to pass your Ajax URL, you have to pass your action, you have to set up your Ajax URL in PHP and then doing something with it. Number one. Number two, by default, the REST API is more secure because using the Backbone.js client and the REST API, it's handling the nonce checking automatically by default. So the Backbone.js client creates a nonce. It then passes that nonce to the REST API. The REST API can check that nonce. So you don't have to worry about all those things. It's automatically more secure. And number three, it's a lot less code. So if I just take out all the code that we don't need anymore, on the PHP side, there are one, two, three, five lines of code that I can just delete. And then another bunch of lines of code here that I can delete. So it makes my plugin more streamlined. And on the JavaScript side, it's this entire block at the top here that I can delete. And I can just, everything is happening just in 15 lines of code. So those are the three reasons why I prefer using the REST API. There are a lot of other reasons that we're gonna get into later on when we talk about authentication, when we talk about how to create things. But those are my three main reasons for getting to know the REST API, using it and learning to replace it. So the next time you're writing a plugin and you're thinking about doing something in AJAX, consider trying to use the REST API instead. Especially if you're just getting core WordPress data, you're getting posts or getting users or getting products or whatever the case may be, I highly recommend using the REST API. Okay, any other questions around the code, around we've done? I'm gonna figure out that filtering thing. I should have done it before today. So we could have filtered by the title as well. That would have made things a lot quicker. But I just haven't got it there with me today. But any other questions around all of this before we continue, please do let me know. If you want to see the final version of this code that I was looking at over here, it is in the GitHub repository, which I will share here in the chat. The main sort of AJAX-only code is on the main branch. And if you switch to the WP-REST API branch, then you will see the changes to both the PHP side of things. I actually left the localized script in there because I wanted it all to work, but you'll see I'm changing WP API there. And then the JavaScript file as well, you'll see the code for loading the posts. I've done it slightly differently instead of giving it post collection. I just called it all posts, but it's pretty much the same thing, creating the collection, fetching the collection, and then updating. Here I actually did something else, that it's post get title. That's another way you can do it. Say post get title and then pass and render. So there's multiple ways that you can essentially do the same thing. Okay, so the plan for next week is to learn how to extend the WP-REST API a little bit. So what we're probably going to do is we're probably going to create our own custom post type. And then I'm gonna show you how to enable in the way that Paul was mentioning for ACF, there's a setting you can set. I'm gonna show you how to do that in code. And then I'm gonna show you how you can create your own end points, how you can create your own filters and various other things. And then after that, we're probably gonna look at authentication. So that's the plan, at least for the next three to four weeks going ahead. I do hope you've enjoyed the session today. I do hope you maybe learned something. If nothing else, if it maybe makes you think about maybe trying to use the WP-REST API the next time you're building a plugin and you need to fetch data in JavaScript plan, I do recommend checking that out. And as I mentioned, the big thing that is using the WP-REST API at the moment is the block editor. And there is a package in the block editor called API Fetch, which does exactly what we're doing today with Backbone. You pass it a route, you tell it whether it's a get or a post and it'll then either fetch the data or update the data or whatever the case may be. Okay, any final questions before we wrap up today? I'm gonna grab a sip of water, otherwise we can call it a day. Where is the final code? So if you go to the Learn-REST-API repository you'll see there's this branch drop down at the top here. So on the left-hand side just above the repository code here says main at the moment. If you click on that and you switch it to WP-REST-API then that changes to the REST-API code. And then you can either click on the API.js file to see the JavaScript side or you can click on the REST-API.PHP to see the PHP side. I am also planning on, if you click on, if you go back to the main repository and you click on releases, I am planning on adding release version 002 which will include just the new stuff, the REST-API stuff. So you'll be able to download that plugin but I only do that after I post the session in preparation for the next session. So I keep an eye out for that. We'll probably use that code next week as people run from here. So keep an eye out for that. Whenever I do these workshops, my plan for this year is always to load that code somewhere as a downloadable plugin so that you folks can download it and check it out. So keep an eye out for that. Okay, awesome. Thank you everybody for joining me today. Thank you for bearing with me as I fumble through how to filter things in the REST-API. I should have prepped that. If that would have been cool if I'd have remembered to prep that for the workshop but I completely forgot. So I apologize. I'll make sure it's ready for the next session. How to filter it using the background client. And as I say, we'll continue for the next couple of weeks on how to use the REST-API, how to extend it. What I'd like to do is maybe think about some of the Ajax implementations you've done and maybe bring some of those along and say, well, how would I do this? Like the person asking about ACF, how would I do a custom Ajax endpoint in using the REST-API? How would I work with, my plan is to work with a custom post type but maybe a custom table might be interesting to look into. So if you've done quite a bit with admin Ajax in previous plugins or previous projects, think about some of those examples that we can look at and we can maybe bring them to a session and then I can plan for a future session how to replicate that in the REST-API. That could be quite fun. I do every Tuesday, I do a live stream where I plan for my Thursday workshop. So if you can send me those examples or those questions about whatever you're struggling with before the Tuesday, you can send them to me on Twitter, you can get hold of me in the making WordPress Slack. You're welcome to on my websites. Let me show you quickly on my websites. And my website is my name, jonathanbossinger.com and there is a about dropdown and there is an about me page. And if you scroll right to the bottom of my about me page there is an email me option. And my email address is linked there. So you're welcome to email me those questions and I'll say, hey, how would I do this Ajax in REST-API or how would I do this or help me with this? And then we can prepare those for a future session. That would be very, very cool because I'd love to be able to show you folks how to completely replace your admin Ajax with the REST-API. And then finally, I just recommend reading through the REST-API documentation. The documentation is very well laid out, very, very clear. It's got a full endpoint reference, a full glossary. It talks about how we're going to get into extending it later on, but it talks about it there. So do read through that and maybe use this plugin as a base and start playing with things and trying things out. Awesome. Thank you all for joining me. Thank you for bearing with me with my power troubles. It seems that my portable battery has lasted very well. So I'm very happy about that. Enjoy the rest of your Thursday and your weekend up ahead, and I'll see you all next week.