learning WordPress & JavaScript in 2019: Coding a Custom Block Type for Gutenberg Block Editor > WordPress learning


Learn how to use WordPress.

learning | WordPress & JavaScript in 2019: Coding a Custom Block Type for Gutenbe…


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


okay you excited for the new year
excited about New Year's Eve no all
right let's go code then hello everyone
this video is gonna get uploaded right
before the start of 2019 in fact
depending on where you live in the world
it already is 2019
just a few weeks ago in the first week
of December 2018 something huge happened
in the WordPress universe WordPress
officially launched their new block
editor now there's a lot of hype
surrounding the editor there's a lot of
fear and confusion
so hopefully this tutorial demystify
some of that and also I thought this was
the perfect video to follow on the heels
of the ten days of JavaScript because
the new block paradigm in WordPress is
primarily powered by JavaScript not PHP
so in this lesson we are going to
continue to practice and develop our
JavaScript skill set just a quick
shameless promotion I actually filmed
this lesson as part of my 25 hour
premium WordPress developer course if
you find this lesson helpful you might
enjoy the full course you can always
check it out on you to me there's a link
to it in the description for this video
also if you're wondering where in the
world the full stack premium JavaScript
course is don't worry it's coming soon
having said all of that I want to send
out a huge thank you to all of my
subscribers I hope you have a beautiful
2019 and let's enjoy this video

hello everyone in this lesson we are
going to learn how to code our own new
block type
now when I say block what does that mean
what's the context here well in versions
5.0 and later of WordPress whenever you
create or edit a page or post so posts
add new this editing experience for the
content uses a block paradigm so as we
type each new paragraph is considered an
independent block right and you can
click to reorder them or drag and drop
to reorder them now these are just
simple paragraphs but there are other
types of blocks out of the box by
default WordPress comes with paragraphs
heading lists columns buttons images you
get the idea but aside from these
default block types that WordPress comes
with we can create our own new custom
block types as developers so right now
let me give you a sneak peek of what we
are going to be building together in
this lesson we see this block type named
my cool border box with a smiley face
and if I click that we see this your
cool border box there's an input where I
can type strawberry and then there's a
color picker
so maybe I will choose a color that
matches strawberry okay and then I can
go ahead and publish this post and then
if I view it on my front end we can see
here are the default paragraph blocks
but here is that custom border box block
we see the word that I typed in and we
also see that color that I chose and
just to show you the reusable nature of
blocks I could add another my cool
border box so if I added it again maybe
this time I will say I like oranges and
then for the color obviously I would
choose orange and maybe I want this
orange box to sit down below the other
paragraph so I can just click move down
to send
down go ahead and click update and if i
refresh the front-end there you have it
now I realize this is very ugly right
this is not the pinnacle of graphic
design but that's not the point of this
lesson our goal with this lesson is just
to get you familiar with the very basics
of coding your own new block type once
you've got a grasp of the basic concepts
it's up to you to take the idea and run
with it
and create something that's actually
good looking and actually useful so
without further ado let's get started
behind the scenes I just removed all of
the code that was powering that custom
block type so now we can start together
and move forward in order to create and
register a new custom block type let's
begin by creating a new plug-in now
earlier in this course we already
learned how to create a plug-in so
that's nothing new so for the next few
steps I'm going to move pretty quickly
but let's begin by navigating to the
directory where you've installed
WordPress and we are looking for the
folder named WP content inside that
we're looking for the folder named
plugins and inside this plugins folder
let's just create a brand new empty
folder we can name it whatever we want
but I'm going to call it my cool border
box okay then let's open up this new
folder in our favorite text editing
program okay in this new folder let's
use the text editor to create a new file
the name doesn't matter as long as it
ends in dot PHP so I chose plug-in dot
PHP and I'm actually just going to paste
in a bit of boilerplate code you can
find this code in the description or
linked resources for this video lesson
because we've already created a plug-in
earlier in the course I'm not going to
type this out letter-by-letter with you
that would just be a waste of time
there's not a whole lot of educational
material going on in this code we're
basically just registering a new plug-in
and then we are loading a javascript
file at
right place at the right time this is
because the new block paradigm is
primarily powered by JavaScript not by
PHP so again I will include a link to
this code so you can just copy and paste
it into your PHP file just like I did
okay let's go ahead and save that file
and now let's create another new file
but this time a JavaScript file so use
my text editor new file I'm going to
name it my dash block dot J yes
technically you can name it anything you
want as long as it ends in dot J yes
I'm going with my dash block because
that's what I've included in the
boilerplate PHP right that's the file
that our PHP is going to try to load
okay now let's jump into that javascript
file and before we write any real code
let's first write an annoying alert
popup message just as a test to see if
our file is being loaded and let's say
this is a test let's go ahead and save
this and then back in the WordPress
admin dashboard let's go activate our
new plugin so in the left hand sidebar
look for plugins so here it is my cool
version 1.0 by brad let's go ahead and
click activate and now let's test things
out to see if our javascript file is
being loaded so let's go to the edit
screen write posts add new awesome
there's that pop-up this is a test that
means our JavaScript is loading at the
right place at the right time and now we
can finally get down to business and get
to the actual educational part of this
lesson so let's get rid of this test
alert and what we actually want to do is
begin working with the WP object that
WordPress adds to the global scope we
can look inside the WP object for
another object named blocks and it
contains a method named register block
type okay within the parentheses we want
to give this method two arguments
so just as placeholders we could say a
comma B the first argument is a name
that we make up for our new block type
I'm going to say Brad slash border-box
the first part of the name before the
slash is the namespace the idea here is
that even if a different plug-in had a
custom block type named border-box there
would not be a naming conflict because
of the beginning few letters and then
the slash so you can just choose your
name or a few unique letters and then
obviously you could name your block type
whatever you want as well okay
the second argument that we want to pass
this register block type method so
instead of B we want to pass it an
object so curly brackets to create an
object literal and then inside these
brackets let's drop down okay and in
this object we want to include several
different properties so type these out
with me title colon for now let's just
set all the properties to a temporary
placeholder X let's just get the
skeleton up and running and then we can
come back and place real values the
title icon category attributes edit and
finally save so this is the overall
Anatomy or skeleton of a block type now
let's start filling in each one of these
values so for title instead of X let's
include a string of text and I will say
my cool border box so you could think of
it as this is the human friendly
readable name and this is the computer
friendly variable name okay next up icon
I'm going to include string of text and
say smiley earlier in the course we
already learned about dasha cons
remember you can google for wordpress -
cons and then choose from any of the
tons of different icons that WordPress
ships with it's up to you I'm going with
the smiley face icon for category I'm
going to say common this just controls
where your block type shows
in the block user interface so there's
common there's layout embeds formatting
widgets you get the idea
I'm going with common four attributes we
want to include an object so curly
brackets let's drop down we can think of
attributes as sort of the raw data that
powers our block when it comes to the
border box that we're building we only
need to keep track of two pieces of data
number one we need to keep track of
whatever text the user types in and
number two we need to keep track of the
color that they select so for attributes
let's say content you could make up
whatever name you want you could call
this text you could call this pizza call
a unicorn the name does not matter I'm
just gonna call it content then we set
this to an object and then we just
describe what it should be so type it
should be a string of text so the
content should not be an array it should
not be a number it should just be a
simple string of text okay let's include
comma here we also want to keep track of
the color that the user selects so color
set that to an object let's also say the
type should be a string right a string
of text or a color code and that's all
we need for attributes right we just
have those two pieces of data they want
to keep track of okay and finally let's
take care of edit and save this is where
the real magic happens so edit controls
the interface that the user sees in the
word press editing screen and save
controls what HTML actually gets output
into the post right so save controls
what you would see on the front end for
that block now for both of these instead
of X what we actually want is a function
so function parentheses curly brackets I
like to drop down inside the body of the
function let's do the same thing for
save instead of X give it a function
parentheses curly brackets now within
the parentheses for both of these
functions let's include a parameter
named props
I don't want to jump into the rabbit
hole of what props is for now all we
need to know is that when WordPress
works with our custom block type when it
calls these edit and save functions it's
going to pass into it different methods
and data and by including props here we
will have access to those methods and
that data all right now within the edit
and save functions we want to return
something so really oversimplify things
we want to return HTML but it's not like
we can just include a string of simple
HTML this will not work instead we need
to construct our HTML in a way that
WordPress will understand and as of the
date that I'm recording this lesson
WordPress is using a library named react
so we want to create our HTML or our
user interface or our Dom elements in a
reactive way now if you've never worked
with the react library before or maybe
if you've never even heard of react
that's a-ok we don't need to know very
much at all about react in order to get
up and running here for now all we need
to know is that in react there are two
main ways of creating an element there's
the manual technical way and then
there's a super easy and intuitive way
let's begin with the easy and intuitive
way now this might seem like a tangent
but trust me it's super related right
now I want you to open up a new tab in
your web browser and visit babel j SEO
or you can just Google for babel j s
from this website i want you to click on
the try it out link up in the navigation
menu okay now check this out in the
left-hand column let's type a bit of
HTML let's create a div element right so
opening tag closing tag and maybe inside
the div tags let's just say hello okay
now let's look at what the babel tool
automatically generated for us in the
right-hand column so we can see that
it's using the reacts library and its
a method named create elements and then
it's passing that method three arguments
so the first thing is the type of
element that you're creating so this
could be a div or a heading level three
or a paragraph right so if I come over
to the left-hand column and change this
from a div to a a four an anchor or link
you can see the automatically generated
code updates right we see an a here all
right now the second argument that
create element takes is the attributes
for this element so check this out over
on the left hand side if we give our
opening a tag an href of just a pound
sign for a test well we see that
reflected in the generated code right
that's the second argument any
attributes for the element and then
finally the third argument is the
content or the children for the element
in this case is just a string of text
right hello but over in the left hand
column what if instead of hello we
wanted to nest a span element inside our
link and that's where we would say hello
well now we can see that the third
argument is another call to react create
element right
this element is nested inside this
element now remember when I said there's
two main ways of creating an element in
react I said that there's the manual or
technical way and there's the super easy
and intuitive way now you might be
scratching your head saying what's going
on I mean the left-hand column is just
HTML but it's not so this looks like
HTML but it's actually a syntax named
JSX JSX is an incredibly useful syntax
where we can write code that looks like
HTML and then behind the scenes it does
all of the hard work for us and converts
it into the appropriate react dot create
element code and that is the type of
code that WordPress wants or needs so
let's get back to the real task at hand
here we want to create an HTML user
interface with maybe a label that says
you're cool border box and then below
that we want an in
field where the user can type in their
words so over on the left-hand column
let's make that happen so maybe we would
have a heading level 3 that says you're
cool border-box and then below that we
would have an input field now I see an
error message right here and that's
because in JSX
you can only have one top level or root
element to get around this we usually
just wrap all of our JSX
in a wrapper div right so div close that
wrapper div out down here we can indent
just to stay organized and now we see a
different error and that's because in
JSX every element needs to be closed so
inside the input let's include the self
closing forward slash now in html5 we
wouldn't need this but this isn't
technically HTML it's JSX
and it's got its own rules and corks and
tips and tricks okay let's say that this
input has a type of text okay now a bit
later on in the lesson below the input
we would include the color picker tool
right about here but for now let's not
worry about the color picker let's just
get our input field up and running first
so we just wrote this intuitive easy to
work with JSX code now what we want to
do is copy and paste the right-hand
column into our JavaScript file we don't
need to include the use strict so I'm
just gonna select and copy all of this
copied into my clipboard back in our
JavaScript file within our edit method
what do we want to return we don't want
to return a simple string of text what
we want to return is the code that's in
our clipboard so paste it in now
technically we could leave this code as
is and it would work as of today because
as of the date that I'm filming this
WordPress loads the react library into
the global scope so we can access it
just like this but there's no guarantee
that it's always going to be that way
right WordPress might change in the
future so the official WordPress e way
of doing this is to get rid of the word
react and
instead say WP dot element dot create
element currently the official wordpress
software is using the exact react create
element method but who knows maybe six
months to a year from now they will need
to modify that method or maybe they
would adopt a different library that's
very similar to react but isn't react
exactly basically this is just an
official WordPress abstraction layer and
while you could technically write react
dot create element this is the
future-proof way of doing things this is
the WordPress way of doing things so
it's a bit sloppy of me to leave react
here as well as down here but I don't
want to waste time in this video having
you watch me change this to WP elements
each time we copy and paste from the
babel tool okay moving on before we save
this file and test it out in the
WordPress admin let's come down to our
save method and within the body of our
function let's just return null this is
just a temporary placeholder eventually
we will want to output HTML for the
front end of our website but for now
just so we can test our edit interface
this will do the trick
so let's go ahead and save the file and
then back in WordPress go ahead and
refresh your edit screen your post edit
screen and now if I try to add a block
it shows up under most used for me but
since you've never used it before you
would need to click into common blocks
that's the category that we chose and
there it is my cool border box go ahead
and click on it and there we see it
there's our heading level 3 and there's
our input field however if we type into
this field green apple and try to save
this wordpress post so publish an update
if I leave this screen and then come
back to that screen so go back into that
post you can see that it did not save
what I typed into that field and this is
because we never told WordPress that
that input field has any sort of
relationship to our content
tribute remember we've got these two
attributes and they are the pieces of
data that we need to hold on to our text
content and the color so let me show you
what I would do let's jump back into
Babel to work with our intuitive JSX
code at this point you might be thinking
to yourself I wish we didn't have to
work in the browser because now we're
gonna have to re copy and paste and it's
awkward to keep jumping back and forth
between the browser and our text editor
well I will let you know that in the
real world professional developers are
not jumping back and forth between their
text editor and their browser like this
in the real world you can set up an
automated workflow so that we could
write intuitive JSX code right in our
JavaScript file here however in order to
set up that automated workflow you would
need to be at least a little bit
familiar with things like node and NPM
in the command line and in this lesson I
don't want to assume that you're
familiar with all of those things so in
this lesson we are going to keep
awkwardly jumping back and forth between
our text editor and the Babel website
but if you are a bit more advanced and
you are familiar with the JavaScript
ecosystem things like node and NPM and
the command line I recommend you check
out this popular package named create
guten block it's going to set up that
automated workflow for you I'm not going
to use it in this lesson so I'm not
gonna run through the instructions but
if you're familiar with NPM and the
command line these instructions are
super easy to follow so this is what I
would use in the real world
so that I could write JSX directly in my
text editor here but in this lesson I
don't want to exclude people who maybe
aren't familiar with the command line
and node and NPM and all of that so
stick with me let's just keep using the
Babel tool for the simplicity of this
lesson okay back to the task at hand we
need to tell WordPress that this input
element is related to our content
attribute right so that that data
actually gets saved and stored so what I
would do is on this input elements I
would give it an
on change handler so on change equals
and then let's include a pair of curly
brackets in this context the curly
brackets tell JSX that we want to do
something dynamic now let's make up a
function name that we will create in a
minute or two from now could be anything
but I'm going to call it update content
so now after every keystroke when the
user is typing into this field this
function is going to be called so then
we can create a function with this
matching name and in it we can update
the content attribute to whatever the
value of this input field currently is
set to now before we re copy and paste
this code into our text editor let's
first add one more attribute to the
input let's say value equals and then
curly brackets and let's say props dot
attributes dot content this way when a
user edits an existing post that's using
this block type the existing or previous
value will be pre-populated into the
input field all right now let's go ahead
and recopy and paste this into our text
editor so copy this back in our edit
method let's change what gets returned
so I'm just going to delete from right
after the word return down to the
parentheses semi-colon delete that and
just re paste in okay and if we just
told this element to run a function
named update content after every
keystroke or every change we better
create a function with that matching
name so within our edit method maybe
right above the line where we return
something let's create a function so
function I chose a name of update
content parentheses curly brackets and
what do we want to do we want to update
the content attribute to do that we can
work with props which is going to get
passed into our function and it has a
method named set attributes we passed
this method an object and we let it know
which attribute we want to up
in this case its content and we want to
set it to whatever that input field
currently contains right whatever the
user is typed in now every time that
input field calls this function it's
going to pass along the event as an
so let's receive that event as a
parameter so in these parentheses I will
say event okay and then what did we want
to set the content to we can just say
event dot target dot value in other
words whatever element called this
function grab its value okay now let's
go ahead and save and take it for a test
drive back in WordPress be sure to
refresh this screen and now in this
field I will type green apple
click update to save that and then if I
leave this screen and come back to it
awesome you can see that it saved my
input alright next let's work on adding
a color picker field right about here
now I have some good news we do not need
to code and develop our own color picker
from scratch we do not need to reinvent
the wheel WordPress has a bunch of
pre-existing components that we can
leverage so check this out if you open
up the JavaScript console for your web
browser while you're on the edit screen
and if you type in WP dot components and
push enter and then if we expand this
you can see that there are all sorts of
different built-in components that we
can leverage and there just so happens
to be one named color picker so let me
show you how we can use this in our JSX
code let's jump back over to Babel and
over in our left-hand column right below
the input field let's create a new
element and just say color picker well
to be more precise in front of color
picker we should say WP components dot
color picker be sure to capitalize the C
in color and the P in picker the beauty
of react is the
can leverage reusable components like
this and basically pretend that they are
native HTML elements now just like we
tied our input fields to our content
attribute we need to tie the color
picker to our color attribute right so
that the value actually gets saved so
let's do this on this element let's give
it a few attributes instead of on change
we want to give it an attribute named on
change complete this way when the user
is dragging the color selector the color
value doesn't get updated a thousand
times per second so the word complete
here will just make sure that whatever
function we pass this will only be
called an appropriate number of times so
let's say unchanged complete equals
curly brackets let's make up a function
name I will say update color okay and
just like with our input field we want
to pre populate it with the existing
value if it has one
now instead of value for the color
picker we want to use an attribute named
color that's just what the creator of
this component chose so let's say color
equals curly brackets and then props dot
attributes dot color okay now let's go
ahead and read copy and paste the
generated code over on the right hand
call them so copy that back in our text
editor now inside our edit method be
sure to keep our update content function
that we created and the only part that
we want to update is what's getting
returned so right after the word return
down to the parentheses semi-colon re
pasted in okay now every time the color
picker field gets updated it's going to
try to call a function named update
color so we want to be sure to create a
function with that name so right above
the return we can just say function
update color parentheses curly brackets
just like we did before we want to call
props set attributes of props dot set
attributes pass it an object and we want
to update the color attribute its value
is going to come from the color picker
now every time that color picker
component calls this function it's going
to pass it its value so within these
parentheses let's include a parameter we
call it value to receive it and then
down here let's say color should equal
value dot hex because we are interested
in the hexadecimal color code
specifically all right at this point
let's go ahead and save the file and
test it out so back in the admin
dashboard be sure to refresh the Edit
screen see green-apple let's go ahead
and choose a matching green color now I
will save or update the wordpress post
and if I leave this screen and then come
back to it awesome you can see that it
saved our green color now let's change
gears the editing experience for our
block is done at this point now let's
focus on the HTML that it actually
outputs right the content that you would
see on the front-end of the website for
this block because at the moment if I
save this post and try to view it on the
front end you can see that the content
area is completely blank and that's
because back in our text editor remember
down at the very bottom of our code the
save method isn't returning anything
it's just returning null so let's write
a bit of JSX that would create the
appropriate HTML that we would want to
see on the front end so let's jump over
to Babel I want to clean slate so I'm
going to completely erase the left-hand
column if you want to copy and paste
this into a blank text editor just for
reference that's okay but I'm going to
delete it okay and at the end of the day
what do we want this block to generate
what do we actually want to see on the
front end of our site how about a
heading level 3 and inside the heading
we would want to see whatever text the
user typed into the field so curly
brackets and we would just say props dot
attributes dot content okay and then we
want to give it a thick border of this
selected color so on the opening h3 tag
we can
say style equals curly brackets to do
something dynamic and then inside those
curly brackets let's include another
inner pair of curly brackets because we
want to pass style an object so the
property would just be the name of the
CSS property in this case border border
: and then we could include a string of
text here so quotes and then say a 5
pixel thick solid red border but we
don't want to hard-code the color value
so instead of quotes for a simple string
of text we can swap out the quotes for
back ticks this is the character to the
left of the one key on your keyboard be
sure to change the closing quote to a
back tick as well and now that lets us
do something dynamic inside this string
of text actually it's no longer a simple
string of text the back ticks turn it
into a template literal and now we have
a superpower so we can get rid of red
and say dollar sign curly brackets
inside the curly brackets we can pull it
in a dynamic value so we can just say
props dot attributes dot color if you're
having a hard time typing this out don't
worry in the resources or description
for this lesson I will include a link
with the final product JavaScript that
you can just copy and paste if you want
to anyways let's go ahead and copy and
paste this generated code into our
JavaScript file so copy that down at the
bottom in our save method instead of
returning null we want to return our
clipboard so paste it in before I save
this one final public service
announcement remember that in the real
world you don't want to leave this as
react you'd want to swap this out for WP
element I haven't been doing this every
step of the way just to speed up the
lesson a bit but you get the idea okay
let's go ahead and save that and jump
back into WordPress now if we refresh
the front-end for that post nothing is
going to change and that's because
WordPress doesn't directly use your
block type anywhere except the Edit
screen so we can't retro
actively update blocks with our code
like that we need to actually go back in
to the Edit screen for that post and as
soon as we refresh this edit screen
WordPress is actually going to show an
error message for the block so check
this out if i refresh we see this
message this block contains unexpected
or invalid content now my own personal
opinion I'm not sure if I agree with
this decision that WordPress made but I
realized that they had good intentions
so essentially any time the output for
your block changes at all so previously
it was set to null when we saved our
block and then obviously this code is
way different than null but anytime the
output of our save method changes at all
it's going to invalidate our block and
WordPress is going to say uh-uh
no way your blocks code is not allowed
to change the users content without the
users permission so it's going to show
this message to the end user they have a
few different options in our case we
just want to delete this block so we can
insert the new updated version of the
block so I'm just going to click convert
to HTML and then delete the block
entirely so remove block and then just
reinsert a new copy of the block so my
cool border box insert it again I'll
need to type in the value again so
choose a green color click update and
now if we go check the front-end and
refresh awesome there's our text and
there is the appropriate border color
just to show the reusable nature of
blocks why don't we add another block
that says banana and it has a yellow
border so back in here we could just add
another my cool border box say banana
choose a yellow
update go refresh the front-end awesome
now that concludes the hands-on portion
of this lesson but at the end here I do
want to address a few common concerns or
questions you might have and I will also
give you an extra credit assignment so
first of all let's talk about that weird
situation where WordPress did not want
us updating the save method let me show
you how this works
so back in our code even if we change
something super subtle so if we change
this from a heading level 3 to a heading
level 4 even something super subtle like
this if I save that and then go back
into WordPress and refresh the Edit
screen WordPress goes nope no way this
block now has unexpected or invalid
content when I first saw this behavior I
thought I was doing something wrong as a
developer or that I had ran into a bug
but this is actually the intended
behavior of WordPress the creators of
WordPress really do not want a plug-in
to be able to change the HTML content of
a post basically without the express
written consent of the user or author
now I understand why WordPress would set
things up this way but in my opinion
this greatly reduces the usefulness of
blocks personally I would never use a
block like this on any of the websites
that I maintain to me the whole idea of
a block is that I would want to be able
to change the code in one location and
potentially have an update hundreds of
instances across my website I think that
would be awesome
however by default that is not how
blocks work you would need to go into
each individual post and not only resave
the post but you would need to delete
the invalidated or outdated instance of
the block and reinsert it so as a web
developer and maintainer of large
websites I can't really endorse using
blocks like this however this type of a
block is great for a sort of site
builder experience or a WYSIWYG
experience or a drag-and-drop editor but
because the data or attributes are so
closely tied and married to the H
tml the whole situation is just super
unattractive to me as a developer and
maybe that's okay right the whole idea
of the new block editor is that it gives
the end user more control but not
necessarily the developer now if you are
a control hungry developer you maintain
websites and you want all the control in
the world from within your code I do
have some good news instead of this
default block that we just created you
can create something called a dynamic
block now I've seen conversations on
github where the creators of the new
block editor sort of discourage you from
using dynamic blocks unless you really
need to so the idea behind a dynamic
block is that you use JavaScript for
your edit method right you use
JavaScript for the user interface in the
Edit screen but then you would use PHP
to generate the output HTML on the fly
and your JavaScript save method would
take a hands-off approach and simply
return null now again I've seen the
creators of WordPress say that you
should really only use a dynamic block
if you really need to use PHP to fetch
something dynamic from the database or
some other PHP heavy task however and
this is the control hungry developer in
me speaking what I think is pretty cool
is to use a dynamic block even if I
don't need to do anything inherently PHP
ish because a dynamic block does not
throw a fit if the output changes
basically if you want to create a
dynamic block you would just set your
save method to return null just like we
had before earlier in the lesson return
null and you would let PHP generate the
output on the fly to do that and again
you can pull up the same documentation
that I'm looking at by googling
WordPress creating dynamic blocks but to
achieve this in your PHP plug-in file
you would just say register block type
include the short name or variable name
of your block type and then give it a
render call back so this is a PHP
you can choose whatever name you want
here and then that function can just
return a simple string of HTML again the
reason I would do this is because you
are free to update the HTML that
function returns as many times as you
want in the future and it's not going to
show this little message right this
block contains unexpected invalid
content now the question is is this
abusing the whole idea of a dynamic
block is this really how the creators of
WordPress want you to create your blocks
probably not or maybe it is the new
block editor has only been out for about
a month or less at the time of this
recording so only time will tell all I
can say is that as a web developer and
maintainer of large websites I love the
idea of dynamic blocks my end users
would be free to use blocks throughout
hundreds or even thousands of blog posts
and then if I just make one change in
that PHP function the users don't need
to go into each individual post on the
admin the front-end of the website is
just automatically updated to me this is
the best of both worlds
the admin editing experience is really
intuitive it's using the react library
it's very fast and modern but the data
isn't so married to the final HTML that
it leaves a bit of freedom from the
developer side all right now the next
thing I want to address at the end here
is the idea of using a custom block to
store a meta value like you would with a
custom field instead of using a block
just to generate HTML in order to show
you what I mean and also just to learn
more about blocks in general let's take
a look at my database all right so this
is the database entry for that post that
I was working on and here is the post
content field before the block editor
this is where just our standard HTML
would live right paragraphs headlines
unordered lists and that's still
basically what's going on I think you'll
be surprised how simple the new block
editor actually is in terms of what it
saves to the database so this is that
first instance the green-apple box and
this is the second instance the yellow
banana box
let's look at the first instance in the
middle we just see a bit of static plain
old-fashioned HTML this is the output
that our block generates but you can see
that before and after that HTML there
are comments the comments say which
block type this section is using and
then right after that on this opening
comment we see an object a JavaScript
object with our different attributes
right content and color at the end of
the day that's all a block is from the
database perspective now we can start to
see why the creators of WordPress did
not want to let your save method change
the HTML output the idea is that the
HTML in this field should be considered
sacred or untouchable once the end user
has generated a bit of HTML nothing
should be able to change it without
their permission and at the end of the
day even though I'm a control hungry
developer I can totally understand and
respect the decision my WordPress to
invalidate your block if this would
now obviously the user is free to change
the dynamic aspects of this output like
the color or the text content but
anything that's not dynamic anything
that's coming from our save method is
not allowed to change now if we were
using a dynamic block this content would
not exist because we set the output to
just be null but these comments would
still be in place so WordPress would see
AHA this section should use this block
type and this is the raw data and
attributes and then as long as you
registered your block type in your PHP
like we saw just a moment ago remember
register block type and then you give it
a render callback PHP function WordPress
would know to use that to generate the
HTML on the fly so no HTML would exist
in the database for that block all right
now on a slightly related topic let's
talk about meta fields or post meta for
example what if we did not want a
traditional block like this that stores
the HTML in the database
nor did we want a dynamic block that is
still going to use PHP to dynamically
insert the HTML on-the-fly what if we
don't necessarily want our block and its
data to be tied to any sort of HTML
whatsoever what if we simply want it to
store these data values like banana and
the color code for yellow what if we
want it to save those values somewhere
else in the database besides this
smooshed together post content field
well that's what post meta is for
metadata it's it's own separate area in
the database earlier in the course we
learned how to query for certain posts
depending on certain metadata values
right this is how you can create
relationships between posts like saying
a certain professor teaches a certain
subject or teaches at a certain campus
creating relationships is just one
example use of metadata big picture
there's a million different reasons of
why you'd want to create metadata for a
post and at first glance you might think
that the block editor isn't going to
play nicely with metadata but that's not
the case it's actually very simple so
let's imagine that I wanted to save this
value of green apple or whatever the
user entered for content imagine I
wanted to save that into a meta field
all you need to do is go into your
JavaScript and up towards the top of our
block look in your attributes area for
content inside the object that describes
content we could just say comma source
should be meta and meta and this is
where you choose the meta name you could
choose anything unicorn
pizza content ok that's step one there's
only one more step because the block
paradigm is powered by JavaScript not
PHP we need to make sure that this
metadata of content is available in the
REST API right because that's how
javascript is going to get access to the
data so in your plugins PHP you just
want to include something like this
this is pulled directly from the
official WordPress documentation all
it's doing is registering your metadata
so for post that would be the name of
your post type
maybe it's professors maybe it's
campuses or maybe it really is just post
this second argument is the name of your
metadata so that could be content or
color or whatever you choose and then
you just need to set the option show in
rest to true
by default the rest API doesn't show all
metadata for a post so this is just
enabling that and that's all we have to
do so now when you type in this value
banana or green apple that's going to be
saved as a piece of metadata for that
post at that point it's up to you how
you use the metadata you access it just
like you normally would from your
front-end PHP theme files or you can
access it with JavaScript from the
arrest API okay and now to close out the
lesson if you are going to be using
metadata you might not want to rely on
your end user having to manually insert
your block if you think about how
plugins like advanced custom fields work
the idea is that your end user is
presented with a predetermined set of
blocks or should say custom fields this
way the end user doesn't have to
remember to insert a certain block or
field the fields are just there in their
face waiting to be filled out believe it
or not the new block system has
something like this baked into its core
so this is the official WordPress
documentation on the block editor there
is a page called templates and
essentially for a certain post type you
can register a block template meaning
when someone creates a new post of that
certain post type you can define
programmatically which blocks should
appear so that way the user doesn't have
to manually insert certain block types
because we can't expect the end user to
know which data we want them to fill in
I think that this block template feature
has tremendous potential but if I'm
being perfectly honest instead of
setting all of this up myself I would
probably just continue to use the
advanced cuss
Fields plug in the team behind that
plug-in have spent thousands and
thousands and thousands of hours
perfecting the plug-in so unless I
needed to do something super custom that
that plug-in did not allow for or unless
I wanted to create my own competing
plug-in I probably just use advanced
custom fields when it comes to metadata
and meta fields
okay now changing gears before we
finally bring this lesson to a close I
want to give you an extra credit
assignment so back into the WordPress
editor I think it would be cool if this
area that says you're cool border box
instead said preview : and then maybe it
would show whatever text you've typed
into this field and it had the matching
border of whatever color you chose and
the idea is that it updates in real time
it updates every time a keystroke occurs
in this field and every time a new color
is chosen now the good news is that
that's kind of the entire points of the
react library every time our attributes
get updated this component is going to
re-render so i won't spoil the fun for
you but i will give you a hint in your
for the edit method right where we have
the input field and the color picker
component all you would really need to
do is adjust this heading level 3 you
could really just copy and paste the
code from your save method so you can
output the content attribute here and
you could output the style attribute on
the opening tag it's a basic example but
I think it'll open your eyes to what's
possible in the editor react really does
create some amazing opportunities for
intuitive user interfaces ok and that
does bring the lesson to a close we've
only scratched the surface of what's
possible with blocks but you are now
familiar with the very basics from here
the possibilities are limitless if you
made it till the very end of this lesson
give yourselves a pat on the back we
covered a lot of ground at this point I
encourage you to go experiment and most
importantly have some fun while you're
doing it take care

댓글 0개

등록된 댓글이 없습니다.

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

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