learning WordPress REST API Tutorial (Real Examples) > WordPress learning

WordPress

Learn how to use WordPress.

learning | WordPress REST API Tutorial (Real Examples)

본문

※ 영상을 선명하게 보기 안내
  1. 유튜브 영상에서 오른쪽하단에 톱니바퀴를 클릭합니다.
  2. 팝업목록에서 "품질" 선택하세요.
  3. 원하는 해상도를 선택해주세요.
※ 모바일에서 Wifi가 아니라면 데이타가 소진될 수 있으니 주의바랍니다.
learning님의 WordPress learning강의 청각장애인을 위한 자막
15777710260441.jpg

 




hello everyone
in this video we will learn about the
brand new REST API in WordPress
now before we worry about what the REST
API is let's just begin by looking at a
demo of the to finished product features
that we will be building together in
this video okay so here's my WordPress
website and if I click on to the
portfolio page there isn't very much
content here but there is a button that
reads load portfolio related blog posts
and if I click that button you'll see
that all of this new content gets loaded
into the page so when that button gets
clicked we use JavaScript or we use Ajax
to visit the WordPress REST API so we
can load content from the WordPress
database into our web pages on the fly
okay so this is the first feature that
we will learn how to build in this video
let's check out the second feature by
visiting the blog page ok this is just a
typical blog listing page that you would
see on almost any WordPress website but
you'll notice up at the top here this
gray box reads quick add post so let's
imagine this is your website and you
want to create a blog post right now
this very second maybe you don't want to
hop over to the WordPress admin
dashboard screen maybe you want to
create a post right from the front end
of your website okay that's exactly what
we can do here
so let's come up with a title for a new
post let's just say testing one two
three and then let's add a bit of body
content for the post sample text for the
demo post and then I'll click the Create
post button and now if I jump over to my
admin dashboard and click on posts in
the sidebar here we see that brand new
testing one two three post and if I
click on it there's the body content
that we typed in okay so we successfully
created a new post from the front-end on
the fly without a page redirect or
fresh okay so those are the two example
features that we will be building
together they may not be super complex
or impressive but they will teach us the
basic building blocks of understanding
and working with the brand-new WordPress
REST API without further ado let's get
started so we've got to begin with the
question what exactly is the REST API
well in a nutshell it's just a
collection of JSON endpoints or URLs so
check this out here's my WordPress
website and up in the address bar at the
end of my site's address if I tack on WP
- JSON / WP / v - slash posts and press
Enter WordPress gives me the ten most
recent blog posts in JSON format now if
you've never heard of JSON before and
you have no idea what's going on right
now that's okay but I do recommend you
pause this video and go watch my JSON
and Ajax video first okay but moving on
even if you've never seen JSON data in
your life
this really isn't that intimidating so
let's dissect it so we see here ID
equals 152 okay so we know that every
wordpress post has a unique numerical ID
okay here we see slug equals testing one
two three so we know that each post has
a slug that is the shorthand URL here we
see title each post obviously has a
title here we see content so this is the
body content for a post you get the idea
so this is the raw data for the ten most
recent posts what if instead of ten
posts I only want two posts well up on
the URL at the end I can tack on a
question mark and then say per page
equals two and now WordPress only gives
me the JSON data for the two most recent
blog posts all right let's try something
else what if instead of limiting the
posts per page what if I only want posts
that belong to the category of opinion
okay so I know that my opinion category
an ID of three so I can say categories
equals three okay so these are only
opinion posts what if I only wanted one
post so the single most recent opinion
post well up in the URL we can combine
multiple parameters so I can just tack
on the ampersand and say and per page
equals one so this is the most recent
opinion post so you get the idea you can
tack on different parameters to retrieve
the exact data you want now I do want to
point out that the word press in the URL
that I'm highlighting right now this is
part of my own local development URL
okay so this is the route URL of my
project so you wouldn't type word press
like this you would only type the part
that I'm highlighting right now so
beginning with slash WP JSON this is
what you would add to the end of your
WordPress site URL also if you try
visiting this URL on your site and you
don't receive any JSON data it's likely
because your version of WordPress needs
to be updated the rest api is brand new
it was just added to WordPress in
version 4.7 you can see what version of
WordPress you're currently running by
logging into your admin dashboard and in
the very bottom right hand corner you'll
see your version number okay let's jump
back to the API tab because I want to
show you that this isn't just limited to
posts so we can do the same thing for
pages and comments or media or users and
authors or settings or you get the idea
just about any piece of WordPress data
is accessible from these endpoints okay
so at this point we have a general idea
of what the REST API is now the question
becomes why is this such a big deal why
are people so excited why are we hearing
that this is the biggest wave in the
WordPress ocean in recent memory well
it's because the REST API makes crud
operations available from anywhere crud
stands for create read update and delete
now when I was typing URLs in
browsers address bar we were just using
the read ability so the are and crud
right we were loading or reading data
but we can also create or save brand-new
data so check out this example if we
send a get request to this URL WordPress
knows to give us back the 10 most recent
posts but if we send a post request to
that exact same URL and we also send a
bit of data along with our request so
maybe we send over a title and body
content WordPress will know that we want
to create a new post and it will save
the data we send into the database now
in this lesson we're only going to learn
how to create and read because once you
understand those two learning how to
update and delete our pieces of cake
okay so the REST API means we can
perform crud operations from anywhere
instead of only from within the
traditional WordPress admin dashboard
screens and this opens the door for all
kinds of new possibilities so for an
example we could technically create an
iOS or Android native app for
smartphones and we could use WordPress
as our server and database layer and the
phone app could just send and receive
data to and from WordPress's json
endpoint urls or instead of a native app
for phones if we were just building a
traditional web app maybe we don't love
PHP so we could build our web app using
nodejs
or Ruby on Rails or Python or any
language we want as long as the language
has the ability to make HTTP requests
and interpret JSON which is basically
every language Under the Sun
so you can see how this is a game
changer WordPress can be our home base
that stores our data but now we can
manipulate that data from anywhere using
any technology stack we want now all of
these different possibilities are
amazing but in this video we're
obviously going to stay a bit closer to
home because the REST API is also great
for building traditional WordPress sites
traditional WordPress themes and plugins
now in this video series we've been
building a theme together so let's stick
with that let's just get down to code
our first example feature so remember on
my portfolio page I want to add a button
right about here and when that button
gets clicked I want to load and insert
new content into the page on the fly now
in order to do that I'm going to need to
write JavaScript so the first thing I'll
do is jump over to my text editor I have
open the folder for the currently active
theme and I'm going to create a
subfolder for my JavaScript files just
to stay organized so new folder I'll
name the new folder j/s okay and then
within that new subfolder I'll create a
new file and I can name the file
anything I'd like but I'll call it main
j/s and just as a test let's log out to
the console a bit of text that says
hello from ajs let's save this and then
our next step is to include this
javascript file within our PHP or HTML
templates now there are many different
ways to do that let me show you the
official or proper way of including a
JavaScript file in WordPress so within
our functions PHP file up at the top
from an earlier lesson we already have a
function named learning WordPress
resources and this is where we are
loading our CSS file so within your
functions.php file if you don't already
have a function that's hooked on to the
WP and Q scripts action go ahead and
copy the code that you see here and
underneath this line where we include
the CSS file let's include our
JavaScript file so we can use a function
named WP in queue script the first
argument is our chance to give this
JavaScript file handle or a name it
doesn't really matter what we name it so
I'm just going to name it main j/s feel
free to make up your own name and then
the second argument is just a path that
points towards the file so to point
towards our theme folder we can use a
function named get template directory
URI so that points to the base of our
theme folder and then we
to concatenate on a path to our j/s
subfolder so /j s and then the name of
the file was mange a s the next argument
is our chance to list any dependencies
so any files that our JavaScript code
depends on so potentially that might be
jQuery or it could be the handle name of
another script in our case our
JavaScript doesn't really have any
dependencies so I'm just going to type
null the next argument is the version of
your script so I'm just going to say
version 1.0 and then the final argument
is whether you want this javascript file
to load in the header or the footer of
your website so if you say true your
file will load right before the closing
body tag which is usually what you want
if for some reason you did want to load
your JavaScript in the header just
change this to false all right so let's
save this and refresh the page and if I
check the console we know that we
successfully included the JavaScript
file because we see this hello message
so now we can go back to our JavaScript
file delete this test code and actually
write the real JavaScript but before we
do that I actually want to adjust the
portfolio page template to add in the
HTML button so to edit the portfolio
template I'll just look in my text
editor for the file named Paige -
portfolio if you want to follow along
but use a different page or template in
your wordpress instance remember you can
always just create a file named page -
and then the name of the slug of the
page that you want to customize okay
hence the name page - portfolio.php
so within my template right beneath the
main content I'll create a button
element which reads load portfolio
related blog posts in order to easily
select this element with JavaScript I'll
give it an ID of portfolio posts button
okay and then below this button element
I will also create a completely empty
div and this is where we will insert the
content
we get from the WordPress REST API we'll
add it into this empty div on the fly so
in order to select this empty div in our
JavaScript let's give it an ID of
portfolio posts container
alright let's save this and jump back to
our JavaScript and I'll create a
variable that selects our button element
so this element so we'll save our
portfolio posts button equals document
get element by ID remember it had an
idea of portfolio posts button okay and
let's create another variable for the
empty div so var portfolio posts
container and to select that element
document get element by ID portfolio
post container if you've never selected
elements with JavaScript like this
before I recommend watching my
JavaScript in half an hour video and
then this code should make more sense
okay but this video is on the WordPress
REST API so I'll try to keep things
rolling now we want to do something when
that button gets clicked so let's add an
event listener so we'll start with that
button element portfolio post button and
then we'll use a method named add event
listener and the event that we're
listening for is the click event when
the button gets clicked and then the
second argument is what we want to
actually happen so you could create a
separate function and list that function
name here or we can just create an
anonymous function and whatever we want
to happen when it gets clicked we can
just type right here so as a test let's
say console.log the button was clicked
so if I save this and refresh the page
notice my console is empty but as soon
as I click that button we see the button
was clicked ok so our code is working
now I do want to point out that this
button will not exist on every single
page of our WordPress website so why
don't we make our JavaScript a bit more
bulletproof by wrapping this within an
if-statement
to only run if that button exists on the
current page so we can just say if and
then we can just type the variable name
of that element so if portfolio post
button that's all we need for the
condition check and then just open up
curly brackets and then let's just cut
and paste this code within the if
statement body now when the button gets
clicked we don't actually want to log
this test message to the console so
let's delete that what we actually want
to do is use Ajax to send a request to
the WordPress REST API to retrieve the
desired data now again this is a video
on the WordPress REST API not Ajax in
general if you're unfamiliar with the
term Ajax and you've never used it
before that's a-ok but I recommend
pausing this video and watching my JSON
and Ajax video first in that video I
break down Ajax piece by piece so you
really understand what's going on okay
but to keep this video rolling along at
a nice tempo I'm just going to paste in
a bit of standard boilerplate Ajax code
now I want you to follow along with me
so in the description for this video
you'll find a link either to my website
or to code pen and that link will have
this exact code that I just pasted it in
so that way you can copy and paste it as
well
okay now the most important line of the
code that it just pasted in is this our
request dot open line so what we're
doing here is we're sending a get
request we want to get data and notice
what URL we're sending that request to
so this is my local WordPress setup the
part that is highlighted but your URL
will be different so right now I want
you to pause the video and replace this
code with whatever your development
WordPress root URL is don't worry later
on in the video we'll learn how to set
things up
so you don't have to hard code your
route URL but for right now it's okay it
won't hurt anything so go ahead and swap
this out with your URL and then this is
the magical part of the URL so we're
hitting up the WordPress REST API and
this endpoint should give us the 10
most recent blog posts okay then if we
jump down a few lines if the Ajax
connection and request is successful we
are saving the response text to a
variable named data again all of this
code will make sense after you watch the
JSON and Ajax tutorial but I want to
keep this video under the hundred hour
mark so let's keep rolling underneath
this line just as a test
why don't we log out to the console the
data variable so we can see what we're
working with so let's say console log
data
okay so let's save that refresh I'll
click the button and when I check my
console perfect just what we would
expect so we see ten objects each one is
a post so if we expand this and click on
this first one this is all of the info
for a portfolio post so here you can see
the slug portfolio post three here's the
title if we drill into that portfolio
post three okay you get the idea so now
all we need to do is use JavaScript to
convert that raw JSON data into human
readable HTML content so why don't we do
this down at the very bottom of our
JavaScript file let's create a brand new
function we can name it whatever we want
let's call it create HTML okay and then
back up within our Ajax code instead of
logging out that data to the console
let's call our create HTML function and
let's pass it the data
okay so then back down within that
function within the parentheses let's
add a parameter to receive that JSON
data we can name the parameter anything
we'd like I'll call it posts data and
then within this function we just want
to loop through that raw JSON data we
want to loop through it to create a
giant HTML string and then we'll add
that string into the empty container div
that we created a bit ago now again this
is a video on the REST API not
JavaScript in general so if you're not
familiar with a for loop or if you've
never worked with an array before that's
okay but I recommend watch
my javascript in half-an-hour video or
the JSON and Ajax video first so let's
create a new variable to store our HTML
string let's call it our HTML string and
for now we'll set it to equal nothing
just an empty set of quotes and now what
we're going to do is loop through this
array of JSON data and for each post or
for each object in this array we will
concatenate on a bit of HTML to our
string so check this out let's create a
for loop we want to keep looping as long
as I is less than the length of this
array posts data length increment I okay
and then for each post we want to
concatenate on to our variable so our
HTML string plus equals to add on to it
let's begin by adding a heading level to
element in HTML and we want to output
the title of each post so we'll add on
data that lives in our array posts data
will use our I've area both to grab the
current object in the array and let's
look at the raw JSON data for a second
to find out how we can access the title
so there's a property named title and
then nested within it there's an object
with a property name rendered and that's
where the actual title lives so to
access that in our JavaScript we would
say dot title dot rendered okay and then
let's add on the closing heading level
to tag next let's output the actual
content for the post right so the body
of text the paragraphs of text so we
could keep adding on to this line but in
order to keep things readable let's just
drop down to a new line and again we
want to keep adding on to our string so
we want data that lives in the array of
JSON so post data get the current item
we want the property name to content and
then just like we did with title we want
to look within it for the property names
rendered ok so this will give us the
paragraphs of text the body text and
that's really all we need to tie
and the content for each post so once
this for loop runs we will be happy with
our HTML string so now we just want to
add this string to the empty div on the
page so if I scroll back up to the top
of the JavaScript remember we already
created a variable for that empty div so
it's name is portfolio posts container
so down in this function after our for
loop let's select that empty div so
portfolio posts container and let's set
its inner HTML property to equal our
HTML string alright let's save this and
test it out looks good so we see a title
and content for each post except we
didn't just want the 10 most recent
posts we only wanted posts from the
portfolio category so to fix that back
in our JavaScript if we scroll up to our
Ajax call on this line where we set up
our get request let's adjust the API URL
that we are visiting so at the end of
the URL we can tack on a question mark
and say categories equals and I know
that the ID for my portfolio category is
6 but you could use whatever category
you want in your particular WordPress
instance so let's save that and refresh
and now we only see three posts because
I only have three posts in my portfolio
category also we could customize the
ordering of the posts so by default it
starts with the newest post and then
works its way backwards but if we wanted
the oldest post to be on top we could
adjust the API URL that we're visiting
so I could tack on an ampersand and say
and order should equal ascending instead
of descending so let's save that and now
if i refresh instead of three to one we
see one two three all right and the one
final improvement I want to make to this
feature is once this button gets clicked
there's no reason to click it a second
time so why don't we remove the button
from the page after it's clicked so in
our JavaScript why don't we wait to
remove the button until our Ajax call
has successfully ran and we've had a
chance to call our create HTML function
so right underneath this line we can
select that button element with the
variable we set up earlier in the video
so portfolio posts button and we can
just use the remove method let's save
this and now when we click the button
perfect
it disappears once the content loads and
that means we've completed one out of
our two example features in this video
before we change gears and start working
on the second feature why don't you
pause the video go get a snack or
something to drink and when you get back
we will learn how to save new content to
the database using the REST API welcome
back let's start working on our second
example feature if you think back to the
very beginning of this video you will
remember that on my blog listing page at
the top of this left-hand column
I had a form that admin users could fill
out that would let them create a brand
new blog post from the front end of
their website instead of having to
switch over to the admin dashboard so
right now let's start working together
to implement that feature now really you
could add that form to any page or any
template you want but in my case I'm
going to add it to this generic blog
listing page so in my text editor the
template file that contains the blog
listing screen is index.php here's the
opening div tag for the main column so
let's add a bit of new HTML to the
beginning of this div to keep this video
moving at a nice tempo I'm not going to
write out the HTML by hand I'm actually
just going to paste in a bit of HTML and
remember I want you to follow along so
in the description for this video you'll
find a link where you can copy and paste
this HTML there's nothing fancy going on
it's just a
if with a heading level 3 an input field
for the title of a potential new blog
post and a text area for the body
content and then a submit button ok so
if I save this and refresh the page the
HTML is completely unstyled it looks
like a mess so I'm going to jump in to
my CSS file style.css I'll scroll to the
very bottom let's add a comment and say
click add form Styles just to stay
organized and again to keep this video
moving along quickly instead of typing
out CSS I'm just going to paste in a bit
of code again in the description for
this video you'll find a link where you
can also copy and paste this CSS into
your file let's save this okay that
looks much better now we just need to
write a bit of JavaScript so that when
someone fills out these fields and
clicks the create post button something
useful actually happens so in my text
editor let's jump back into our
JavaScript file I'm going to scroll down
to the bottom let's add a comment just
to stay organized
click Add post Ajax okay let's begin by
creating a variable that selects this
create post submit button so we'll save
our quick add button equals document now
throughout this video to select elements
with JavaScript I've been using document
get element by ID but you can also
instead say document query selector and
then you can just provide it a CSS like
or jQuery like selector so remember that
quick add button had an ID of quick add
button so we can just say pound or hash
tag for the ID quick add button ok now
we want to add an event listener so we
want to be on the lookout for that
button getting clicked and because that
button doesn't exist on every single
page of the website I'm going to begin
with an if statement so we'll say if
quick add button okay so only if
we're on a page where that button exists
do we want to set up an eventlistener so
then we will select that element so
click Add button add event listener
we're listening for the click event and
then we'll supply an anonymous function
so whatever we type here is what will
happen when this button gets clicked so
let's write a bit of standard Ajax code
we want to send information to the
server so let's create a new variable we
can name it whatever we want let's call
it create post and we'll set it to equal
a new instance of the web browsers XML
HTTP request so now we will use that
create post variable and say open the
first argument is what type of request
we're sending so if we want it to load
data or read data from the server we
would send a get request but in this
case we want to send data to the server
so we want to make a post request okay
and then the second argument is the URL
that we want to send our request to so a
pair of quotes and then I'm just going
to paste in my local WordPress dev
environment root URL so that would be
something different for you a bit later
on in the video we'll learn how to set
things up so you don't have to hard code
this root part of your URL like this but
let's keep things simple for now so at
the end of your dev environment URL
be sure to add on slash WP JSON slash WP
/v to remember this is the WordPress
REST API part of the URL and then we
want slash posts now you might be
thinking hey isn't this the URL that
will retrieve the 10 most recent blog
posts well yes if we send a get request
but since we are sending a post request
WordPress will know what to do it will
know that we want to create a new post
so then our next step is to drop down
another line and use our create post
variable and just say send so within the
parentheses of this send method is where
we include the data from our form
we want to send along so that means we
need to use JavaScript to extract the
value of whatever the user types into
these fields so to do that above our
create post variable why don't we create
a brand new line and let's create a new
variable we can name it whatever we want
let's call it our post data and let's
just set it's equal an object now the
name of our object here doesn't matter
but what does matter is the name of the
properties that live within it so for
example we want to be sure to have a
property named title this will be the
title of the blog post and we want to
set this property to equal whatever the
user has typed into this first field so
let's select that input field so
document I will use query selector let's
go look at our HTML so I'm trying to
select the value of this input I could
give this element an ID and then select
it by the ID but instead I can select it
by its name value now just in case there
are multiple forms on the page let's
begin by selecting our admin quick add
div so query selector period for a class
admin quick add okay and then I want to
look inside that div for the input field
element that had a name of title this
code will select that element and then
once it's selected we want to tack on
dot value in order to get the text that
the user is typed all right then let's
add a comma because we want to add
another property to this object we want
our blog post to have a title we also
want it to have content so if I look at
the HTML again now I want to select this
text area element we can see that it has
a name of content so back in our
JavaScript I'm just going to recycle
this line of code so copy paste and
change the name that we're looking for
from title to content
all right let's add a comma here drop
down to a new line because there's one
final property that I want to add
to our object and that is status this is
where we decide if we want the post to
be saved as just a draft or if we want
it to be finalized and actually
published I want to skip the draft phase
so let's just say publish all right and
now our object is complete so these
property names will line up with what
wordpress is on the lookout for it's
expecting these property names and then
if we scroll down when we actually send
our ajax request within the parentheses
of the send method let's just include
our our post data okay so that's what
we're sending to the server but we
probably shouldn't send just a raw
object to the server so instead what we
can do let's delete this and what we
want to do is convert this javascript
object into a simple string of text okay
and then it's up to the server to
reinterpret that string as JSON so
within our send we can just say JSON dot
stringify and then pass it our object so
our post data
alright this line looks good before we
save this and test it out in the browser
there's just a couple more things we
need to take care of we want to be sure
to spell out exactly what our Ajax
request is sending because we know that
we're sending JSON but we want to let
the server know ahead of time that
that's what we're intending to send so
check this out right above our send line
let's add a new line and let's say
create post and then let's use a method
named set request header okay and for
the first argument we want to say that
we are specifying the content type and
then for the second argument we just let
the server know that we want to send
JSON so we say application slash JSON
and we also want to let the server know
what character set we're using so care
set equals utf-8 all right and now we
are only one step away from having this
code work our final step has to do with
authentication and security so WordPress
takes care of the base
security when someone fills out this
form and tries to send an AJAX request
wordpress will only honor that request
if it's from a signed in user okay so
that basic level of security is baked
into the WordPress REST API by default
but in order to make things even more
secure and prevent cross-site exploits
WordPress requires us to send along a
unique code for the currently signed in
user with our Ajax request so let's do
this above this line where we just set
the request header let's create a new
line and we want to send another request
header so create post set request header
this time we want to send something that
WordPress is on the lookout for it's
name is ex WP nonce
I believe this stands for number used
once so I'm not exactly sure how to
pronounce it but that's not important
okay and then the second argument is
just the secret code for the currently
signed end user now obviously we have no
way of guessing what that secret code is
but what we can do is use PHP to output
or echo that code into the HTML for the
page and then we can use our JavaScript
to reference that so to do that let's
jump into our functions dot PHP file and
remember earlier in the lesson when we
included our JavaScript file well within
that same function right below that line
where we include the JavaScript let's
just drop down and we can use a function
named WP localized script ok the first
argument is the handle or name of our
script file so main j/s that's the
WordPress name we gave to our JavaScript
file earlier the second argument is the
name of the object that we want to
output or echo into the HTML so we could
make up any name we want let's just call
it magical data and then the third
argument is an array of what we want to
output so for example I could say mood
equals happy sky equals blue
grass equals green you get the idea
and if I save this and refresh the page
and view the HTML source and then search
for the object name of magical data here
we see it so that PHP we just wrote will
output a bit of inline JavaScript
creates a variable named magical data
and then it's just the JavaScript object
so property mood with a value of happy
property sky with a value of blue you
get the idea so let's go back to our PHP
let's delete these example properties
and remember what we really want is the
code for the currently signed in user so
let's say nonce equals and to get that
value we can use a wordpress function
named WP create nonce and for the
argument we can just say WP rest
alright let's save this file and jump
back into our JavaScript so now in our
Ajax request when we are setting the
request header for the WP nonce we can
access that code so within the HTML
there will be an inline JavaScript
object named magical data and it will
contain a property named nonce let's be
sure to add a semicolon at the end of
this line let's save it and let's go
test things out so I'll add a sample
title testing for the video add a bit of
content lorem ipsum 1-2-3 hit create
post obviously we'll need to work on the
user experience a bit let's go see if
that worked so in the dashboard let's
refresh the post listing I don't see the
post so that means it didn't work let's
jump back to this tab and check the
console for errors okay so we've got an
error missing closing parentheses in our
JavaScript on line 41 so line 41 ah I
see the problem so we used double quotes
within the selector right here and you
can only use double quotes within the
selector if you're outside containing
quotes are single quotes so let's swap
that from a double to a single and then
this closing quote swap it to a single
let's do the same thing on line 42 so
swap that with a single quote swap this
final quote single quote save it refresh
it
testing one two three four lower run if
some create post check the dashboard
perfect there it is so if we click on it
there's the title and there's the body
content so we just created a brand new
post using Ajax and the WordPress REST
API now before we end this video why
don't we improve the user experience a
little bit so if our Ajax request is
successful in WordPress creates a post
why don't we clear out these two fields
for the user and if our Ajax request
fails for some reason we can just alert
a popup message that says error try
again I know that's not the pinnacle of
user experience but I think it'll be a
good example to work on so back in our
JavaScript after our Ajax send line
let's create a new line use our create
post variable and say on ready state
change we'll set it to equal an
anonymous function and remember that a
and Ajax stands for asynchronous so
before I try and check to see if the
Ajax request was successful or not
I first want to wait and give it time to
actually complete so we use an if
statement and we'll say if our create
post only if it's ready state equals for
only if that's the case do we want to
try and determine if the post was
successfully created or not the ready
state will change from one two three
four as it works through the stages of
initially sending the request and
waiting to hear back from the server you
get the idea so for is when it's
complete so once it completes then we
want to run another if statement to see
if WordPress successfully created the
post or if it ran into an error so we
can check that by saying create post we
want to look at the status property and
WordPress will return a value of 201 if
it successfully created the new blog
post entry okay so if that's the case
we'll do one thing
but else otherwise that means we ran
into an error so if there's an error why
don't we just alert a popup message that
says error try again
super helpful right and if it did
successfully create the post why don't
we clear out these two form fields so
that way the user could start typing and
creating another post so let's select
those input fields here we already have
the selector up here so I'm just going
to copy and paste it so I just want to
set that fields value to equal an empty
string okay and then let's do the same
thing for the other field so let's copy
and paste this set its value to equal an
empty string okay let's save this and
refresh in the browser so if I leave the
two fields blank and hit create post
perfect we see the error message pop up
error try again but if I fill them out
correctly this is a test hello world it
was successful and we see that it
cleared out the two fields for me so I
can start typing a new post another post
array and you get the idea so at this
point our feature is complete but you
might be wondering what if someone who
isn't signed into WordPress visits our
website right so currently I'm using
Google Chrome and I'm signed in as the
admin of this website but if I view this
website in a different browser so this
window is Mozilla Firefox and in this
window I'm not signed in toward press so
I obviously should not have permission
to create a new blog post so if I try to
you see that I get an error and that's
good that means WordPress is taking care
of permissions and authentication for us
but if someone isn't signed in as an
admin it doesn't even make sense to show
them this form in the first place so
what we can do if we jump into our
index.php file here's the HTML for that
form why don't we just wrap this in an
if statement so drop into PHP if
and then we can use a function named
current user can and we only want admin
users to see this form so for the
argument will just say administrator all
right and then after this if statement
will include a colon not a semicolon and
will drop out of PHP and then right when
the HTML for this form ends so on this
line we'll just drop back into PHP close
out the if statement so end if drop back
out of PHP and there you go so save this
and then go back to firefox and refresh
remember I'm not signed in on this web
browser perfect so now I can no longer
see that admin form but back in google
chrome where I am signed in it's still
in place ok now we just have one
remaining detail to cover before we end
the video remember earlier I promised
that I would show you how to set things
up in your JavaScript so that you don't
have to hard code the root URL of your
WordPress project wouldn't it be nice if
we could just include a variable instead
of this part of the URL because then our
code would work whether we are testing
in our local development environment or
if we push the code up to our production
live website so here's what I recommend
doing let's jump into our functions PHP
file and remember earlier when we set up
this WP localized script function this
is where we created our magical data
object and we stored the nonce code well
inside this array we can just add on
another property to our object we can
name this property anything we want
let's call it site URL and let's just
set it to equal the results of a
wordpress function named get site URL
let's save this and then jump back into
our JavaScript remember the property
name here that we're interested in is
site URL so in my JavaScript let's just
delete this hard-coded part of the root
URL so now all we are left with is the
API part of the URL and then right
before this we can just say magical data
remember that's the name of the object
that our PHP creates and outputs as
inline JavaScript
then we want the property named site URL
and then we can just concatenate on the
API part of our URL okay and if I scroll
up remember we also had the hard-coded
URL in our get request from the first
example in this video so let me swap
that out delete this magical data site
URL concatenate on that part of the URL
okay let's save this go back to the
browser refresh let's take it for a
quick spin URL variable post-test
testing one two three perfect and if we
go back to the portfolio page and click
on this button to load the content it
still works as well and that's going to
bring this video to a close thank you so
much for watching I know this was a long
video I think this is the longest video
on my channel but we had a lot to cover
with the new REST API I hope you feel
like you learned something and I hope
this sparked your imagination because
just with the concepts we learned in
this video you can create all sorts of
new features this really opens the door
of what's possible with WordPress and it
makes ajax a breeze anyways thanks for
stopping by and i will see you in a new
video next week
so until then take care in case you're
interested I am working on two brand new
premium WordPress courses one is aimed
at absolute beginners and the other is
more advanced and it's aimed at
developers in the more advanced course
we will create a fully featured site for
a university we'll learn how to create
relationships between different types of
content so for example between
professors and courses and campuses
we'll also learn how to set up live
search results using the brand new
WordPress REST API we'll learn the
basics of user registration and we'll
also learn how to keep our project
organized and how to deploy it from your
local dev environment up to a real host
now these two courses won't launch for
another couple of months but if either
of them interests you and you want to be
notified as soon as they do launch you
can go to my website learn web code calm
and towards the top of the home page you
can join my newsletter not only will
that let you know as soon as the core
is launched but you'll also receive
hugely discounted coupons one last thing
you'll never ever ever see this channel
with a patreon account because if you do
want to support this channel I want you
to receive massive value in return so I
do already have two premium courses
available the first course is about 9
hours and it will teach you HTML and CSS
from absolute scratch and the second
course is about 15 hours and it's for
you if you already know HTML and CSS but
you want to build up the rest of your
skill set so you can land a full-time
job as a web developer all right that's
enough shameless promotion I will see
you in the next video

댓글 0개

등록된 댓글이 없습니다.

본 사이트의 컨텐츠는 명시적으로 공유기능을 제공하고 있는 공개된 자료를 수집하여 게시하고 있습니다.

저작권, 강의등록, 광고, 제휴등은 "관리자에게 문의"로 메세지 주시면 확인후 답변드립니다.

Menu