Part 12 - WordPress Theme Development - How to Create a Custom Meta Box

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys Alex here thank you for checking this video and welcome to the lesson number 12 of the series of tutorial on how to build a premium theme for WordPress welcome again in the previous two lessons we created a custom section in the administration panel to activate a built in contact form and with this activation we hooked an action for WordPress to create a custom post dives for us to collect all the messages that a user will send by using the contact form that in the future we're going to create when we're going to build our front-end what we have to do now we have to create a custom meta box to accept an input that usually is not a default input of WordPress if we go inside this post that I created as a test we can use the title of the post to collect the name of the user that it's sending the email we can use the body the message the standard visual editor of WordPress to collect the actual message that is going to send and now we need a custom element we need another field to collect the email we want to save also that data at WordPress gives us the ability to create a custom meta box to create whatever data and save whatever data to all the posts or pages or custom post types that we want so let's take a look on how to do it let's access our text editor and let's stay for now in the file custom - post - type dot PHP because also the meta box even if is not strictly related to the custom post type these meta box is strictly related to the contact custom post type that I created and also in this case I don't want to create the action here I don't want to add the action if the contact form is not active so also in this case I have to put the hook of the action inside the if statement to check if the user wants actually the content form so let's scroll down till the end of our code let's create a comment here and let's write contact meta boxes because maybe in the future we could extend if you want you could extend this functionality you could extend the form by collecting the phone number or the business name or whatever other field you want to collect in your back-end you can totally do it with the same functionalities that we're gonna take a look now that we're going to use right now so let's start by creating a custom function call as usual a unique name so sunset underscore add underscore meta underscore box this is pretty generic so let's use sunset underscore contact underscore add meta box brackets no parameter needs to be passed curly brackets let's open the curly brackets and inside here we can write the code to activate a custom meta box to activate the custom meta box we have to use a pre-built functionality of WordPress that as usual if you already notice right now WordPress uses the functions name basically identical to the action that you want to achieve so also in this case is going to be add meta box because of course we want to create a meta box so the function is called add meta box pretty straightforward the first parameter is the string ID is really important because it's as usual the unique ID that we're going to use to update our meta box to retrieve whatever information is inside this meta box so let's use this ID as contact underscore email the title is the title that is going to appear in the actual box that is going to be generated inside our back-end so inside here user email uploader the callback function also this one really really important because without the code the function we cannot generate any code we cannot put any HTML so the callback function has to be a unique called the function and in this case it's sunset underscore contact underscore email the screen option gives us the ability to print a meta box inside whatever post page or custom post type we want to put our meta box so in my case I want this meta box inside the contact Sun set custom post type and I know that the actual ID of my custom post type is sunset contact so AF to just print this one in screen sunset contact we don't need any context any priority or any callback arguments for these meta box in the future we're going to take a look at what those option are neat for but for now these standard four attributes are more than enough to create a custom meta box let's save it let's put a semicolon at the end of course as usual let's not forget it and this function is pretty much it so now with this function we created we activated the code of the meta box now we have to call the we have to create a callback function to actually generate as usual the HTML that is going to be inside our administration panel and as a generic rule when we use a callback especially when we start adding a lot of functions that I have the same name this one is called contact is one is sunset contact so they're pretty similar if it's a callback you can put callback at the end of the name of the function so you will know that all the callbacks function they finish with Kovacs are related to an actual action or an actual hook or WordPress and our old callbacks function so just to maintain a little bit of clarity while you read your own code or see if someone else is reading your code so let's create this callback function by writing function and let's copy paste the exact same name brackets and inside the brackets and wanna pass the post variable that it's going to be automatically passed by the add meta box and it's going to carry all the information related to which post is this meta box used for so in my case is the custom post type sensor contact so this post variable is going to have inside all the information the ID title slug whatever we pretty much will use only the ID of the post but we have to pass this variable inside the brackets in order to use it curly brackets to open the function and inside here we can start writing a lot of code and you will notice that you manage Update save and properly code a meta box it requires a lot of code but the good thing is that the code is always the same so after you do the first meta box you can reuse the code with a for each function to generate all sorts of type of meta boxes so you don't have to rewrite the code multiple times but bear with me let's take a look on how to do it and let's learn how to use this amazing functional WordPress so first of all we have to use the WP underscore nonce underscore field if you follow this series of tutorials since the beginning you know that the nonce is a pre build functionality of WordPress that generates a unique a unique ID a unique value a unique string like encoded string to check if it's the action whatever action of saving or deleting or updating your information is legit from a legit user inside your administration panel these nuns it's really important to avoid that someone else outside may be a hacker someone is trying to hack your system and is trying to send information to update or to access your database so these nonce is really important so let's specify a bunch of option here and the action is of course a unique action that we will use in the future to refer to our nan so in my case it's going to be sunset underscore save underscore email underscore data and here the string name I can use usual sunset underscore meta underscore box underscore let's use sunset underscore contact underscore email meta box non c'è and the last two parameters we can leave it empty because we don't need to use it right now we're going to take a look in the future how to use also the last two parameters let's keep going and let's collect the value whatever value these meta box is going to have we'd a unique variable so let's create a variable called value and inside here we can use a function or WordPress to retrieve the value of a custom meta box and the function is get underscore post underscore meta and inside here we have a bunch of options let's put a semicolon at the end first we have to specify which post ID we want to use to check our post meta and of course as I said before we already have the post variable and inside the post variable is stored the ID that we can acts inside the object so let's use post meta - bigger than so we have to use this little arrow that is stander of PHP to access an attribute inside an object array so let's put ID that is the unique attribute of the post and inside here we have to use a unique string K that we never used so we have to specify a unique K that in the future we're going to use to also update this meta box information so in my case I want to use om and as a strict rule for all the string value for our meta box they have to start with an underscore before the actual name so let's use the contact email underscore value underscore K and the boolean we have to specify if this value is a single value or multiple value maybe it's an array or maybe is a checkbox with multiple checklist for now for us is just a single value so we have to if I threw because it is a boolean so through we are gonna say to WordPress this is just a single values not an array of values whatever so value is a single string that we need to use and now with a simple echo function we can print whatever information we want inside our meta box let's create a label and in order to maintain this tutorial as simple as possible I'm going to use the exact HTML standard of WordPress own I'm gonna create a meta box that looks like a prebuilt wordpress box a preview WordPress function so I'm not going to create a custom look for this box but you can totally do it with by editing CSS and applying standard applying your own classes to these standard HTML string so let's create this label let's put a label for and let's put D ID has to be of course a unique ID so I'm gonna use sunset underscore contact underscore email underscore field and as you notice here that could be confusing because we're using a lot of this sunset contact email we have the sunset contact email callback we have the sunset contact email meta box non c'è we have the sunset save email data the unique string contact email value k and now we have another ID so we have a lot of different options a lot of different ease and keys unfortunately this is how the meta box works and we have to create all these different IDs and all these different field to properly use the meta box so if you get confused try to as I'm doing right now try to put as an append every time you write a unique ID or unique string of what is this drink for so in this case this is a call back let's put call back at the end this is a nonce let's put the nonce at the end this is the value okay let's put value okay this is the field let's put field so even if you're using always sunset contact email we can put as a and whatever type of string Aggie field we're using to try to keep everything as clear as possible so let's close the heckle with a semicolon said here we can put user email address and let's close the label string semicolon as I said before and here we can echo again the actual input field so that's right input type I want this input to be email we can use html5 to specify this this input has to be email so it's going to have a zone validation even if we manually add something if the email address is not correct is not a legit email address the html5 field text type input type is going to trigger an error is kind of like standard you can put a standard text but we can use html5 sometimes not everywhere but if we can use it especially in the back end it's a good thing let's put the ID and the ID has to be identical of the for D ID that we specified here in the label so it's sunset contact email field and the name has to be identical to D ID and the value now we can put finally the value that we arrived before the get post meta the actual value key that is connected to our post of course in the first case in our case is going to be completely empty what we needed before printing the value as usual here in a PHP function we put single quote to interrupt the string of the echo we put two dots to connect string and a variable you should already know that if you're following my tutorial and but instead of just printing the value here this value can contain some weird HTML stuff we don't really know why it's related to user input so something that I use externally from our administration panel wrote inside this field it's always better to escape the attribute with the pre-build functionality here to escape the attribute so in this way we're going to sanitize a little bit this value and we're going to avoid to have a bad surprises as a last value I'm going to use a prebuilt value WordPress that is usual standard WordPress meta box input value and it's the size of 25 so I'm specifying the size of this input field let's close the input weight a forward slash and this bigger than symbol and semicolon at the end and we wrote the entire callback function to generate a nonce retrieve the value that it's saved inside this meta box and printing the actual input of this meta box now what we have to do we have to finally call the hook to activate this function and activate the actual and meta box what I say before I want the hook to be inside Heath contact it's equal one so if the contact form is actually active I can use the action to activate my function to generate the meta box so the usual hook is add action and the name of the action that I want to use and I have to use to trigger a meta box is add underscore meta and score boxes of course as usual the logic of WordPress is pretty straightforward and inside here as a string as usual f to print I have to put the function name that I want to call so the sunset contact add meta box mmm save it let's go back in our administration panel let's refresh whatever page and now we have the user email contact field here we have the user email address weight of course nothing saved inside we can style a little bit more this thing we can put maybe a column a little bit of space maybe right address in a proper way and just avoid spelling mistake and let's go back here refresh it and now looks slightly better so by default WordPress is putting a new generated meta box at the end of whatever we have so if we're using plugins or Yoast SEO plug-in or whatever other we have an excerpt here your custom meta box is going to appear by default always at the bottom always at the center but what if we want this on top of everything or we want this on the sidebar we can easily do it by using the last two options that I skipped previously for the add meta box function so if you remember the last two options where the context and the priority the context is necessary to specifying which part of the page I want my meta box to be and you have three options so the first option is normal and if we put normal as a context and we gonna take a look we refresh it of course is normal he's here because it's the normal the standard status of the generation of WordPress where is this thing going to be print if we want to put it on the side the parameter we can use as a context of course is side and that it's what I want to use so if we refresh here we're going to notice that our user email input field it just magically moved on the side so we're gonna have everything here nicely organized and that's what we want it we have the other parameter working specify the sixth parameter that is the priority and the priority has four option high core default although so if we put of course the default is going to appear whatever WordPress once if we put high and we save it and we take a look refresh you will notice that because we put high is actually on top of everything so by default we can put maybe these is an advanced position high if I want the email to be right underneath the text the title I can normal but as I said before I want to be on a side and on a default position so let's put default or we can avoid to specify whatever value because the default value of the meta box is actually default so let's save it on the side let's refresh it and it's back in this position so you can play with these settings and functionalities and see where you want your meta box to appear in which position so now of course if we write something like Alex at something calm and we update the post is a data without whatever option but here nothing gets updated so we are losing we're not maintaining whatever value because of course we didn't create the actual function to save our meta box and if you remember here in the nonce field we specified a unique function name that is the sunset save email data so that's what we're gonna use to save our data and because this is generic I want to actually rename these to sunset save contact underscore email data so it's more obvious that's what I'm doing so let's copy this stream let's specify here and let's create again a function with the same string and inside here we can put brackets inside the brackets we can pass the post ID variable basically the nonce will pass automatically to the string the post ID of whatever post we are updating so it's pretty good curly brackets open the curly brackets and inside here we have to do a lot of things we have to check a lot of stuff and it's gonna be kind of slightly confusing but follow me so first we have to do a lot of security tests so we have to check with if statement if it's clinician mark to say that he's not if is not ESET so if he's not set the dollar post square brackets we have to check if the nonce is not set so these nuns that we're generating here this is the unique string name of the nonce if this is not set so we are checking if whatever post message when we save something when we save a post a page or whatever WordPress is going to send all these information with a post method of PHP so inside this post method we can retrieve if these non set that we generated here it exists and this variable is checking if this nonce is not existing open the curly brackets we can just put it on hard return so we're gonna stop the function if this meta box the nonce meta box doesn't exist just stop the function with a return so we will avoid to save whatever information to update our post if this nonce it doesn't exist so it means that the action wasn't actually launched by an administrator the other check oops not a single code the other check that I want to do it is if the nonce is valid so I have to be another if exclamation mark to revert of course if is not valid and we can use a rebuild function of WordPress that checks automatically for us if the actual nonce that has been generated here is a valid nonce generated by WordPress and not generated manually by a or another user so let's use this function called WP underscore verify underscore nan sir and inside here we have to specify two parameters the actual nan set that is exactly identical to this one so the post nan set that is passing the second value is the actual function that is saving my meta box so is the name of this very own function let's put it here and of course also if the WP verify nonce returns false so is not true let's put a hard return and let's stop this function this saving function to be trigger the other check that I want to do I want to verify if this is an outer save or is a manual save because if you know WordPress sometimes while you're editing a blog post is if you spend a lot of time here and you write stuff WordPress sometimes will roll you will notice maybe a little icon that it's saving a draft so for us it's saving multiple revisions of the same post this is really useful but maybe for this email we don't want to actually save these information if is an outer save if it's not something that the user is actually clicking on the Save button so we can check if is defined and the global variable it's a global value specified by WordPress at the beginning this global variable is doing underscore Auto save and double ampersand is doing our save is actually specified it actually exists so if it's defined and it's something here so it's not false is not like completely empty we have to return it so it means that if WordPress is doing the outer save and it's saving by itself the information we don't want to save the meta box so return it of course you can totally remove this one if you want also key meta box to be saved automatically with the outer save but for as a safety precaution is better to avoid it the other check we have to before saving we have another couple of checks so we have to check if the user has the actual permission to write to update and to change the options or whatever information side is meta box so let's check for users permission with f exclamation mark as usual to check if is not we can check with a pre-made function of WordPress a user the current user has the ability the capability of editing a post so we can check it with a function called current maybe right current underscore user underscore can so if the user can as a first parameter edit underscore the post and the second parameter has to be the post ID that we're passing so we're checking if the user can edit this post and we are putting the exclamation mark to say if the user cannot edit this post also in this case let's put an hard to return to avoid to fulfill this saving application okay now what we have to do finally we have to retrieve the data that has been passed so also in this case we have to put F is set so we're checking again inside the post variable of PHP if it's set our field whatever field we're putting here and the field has to be the exact same ID that is specified in the input or dedi or the name these two variable these two parameter should be always identical so let's grab the name ID whatever is the same so if is not set this thing we can also in this way return and avoid to trigger whatever function we're going to trigger finally right now so we're checking if the actual saving of the post is passing this contact email field if it's not passing we don't have to trigger the option to save it so we are pretty good now we checked with this one two three four five options all the pretty standard safety precaution of WordPress we checked if the meta box is East is the nonce is east if is doing an outer save if the user is has the capability to do that and if we actually have the value so if we have the post value of these custom meta box now we can finally create a variable call my underscore data or whatever name you want to give to this variable and we can collect this post contact email field before connecting though and semicolon at the end maybe let's put the dollar sign before collecting before saving updating the post I want to sanitize this text field so let's use the pre-built function of WordPress called sunny ties and the score text underscore field put it here let's put it inside the brackets so we are pretty good with whatever information a user is going to input of course we're going to do some check also in the front and to avoid that the user is putting some malevolent code inside our input field but even if we are checking this let's always sanitize this text field to be sure that nothing wrong is going to be saved inside our database and finally we can call the function called update underscore post underscore meta and the update underscore meta accepts for variable we have to use just three variables so the last one we don't need it the first is the post ID that if you know we actually have it inside here so let's specify the post ID so update the data on this post ID we need to specify the key of whatever data we created so we actually need the meta box key the get post meta that we create a year so the contact email value key because we're going to store this field inside these matter keys so we're going to save this meta key as a string and then we have to pass the value that we want to say then in my case is the variable my data that contains the email information and semicolon idea finally now we have to create a hook to save the post and also in this case I want to put these action inside the if statement here to be sure that this actually is not going to be useful or usable if the contact form is not active so let's call ad action and is action is gonna be trigger during the save underscore post timing of WordPress and the action that I want to call of course is the saving function that I just created this sunset save mm-hmm pretty here as string says contact email data and semicolon at yet save it let's go back in our administration panel let's refresh it let's write Alex at something comm update and the post as updated and we have finally the he mail ear so if we refresh we go back here we go back inside we have the information here so we finally finally after all these checks created a meta box with a custom value a custom information and we are storing these meta box with these posts so these Merida box belongs to this post so what I want to do now to conclude I want to print the email information the email address here in the column to do that it's pretty simple I need just basically to reuse this code that I'm using to retry the data so let's copy these and let's go in the section that I use to customize the column that are appearing in my main page of the messages custom post type so instead of here in the case of the email instead of echoing the email address I can just create a variable called email equal get post meta instead of post ID inside here I have a ready da D printed safely here so let's replace this variable this is the actual value ki ni of the true to specify that as a single and then I can finally safely echo this variable save it let's go back in our administration panel refresh it and we have the him here if we want off so we have full control here to put up whatever HTML string to make this email clickable so a H ref equal mail to column let's reuse the email let's closed a tag let's put a dot to connect the string dot single quote and closed a tag save it let's go back in our administration panel refresh and now this one is linked that it's connected directly to the email so if we click here it's going to open our email software email client with these email already input in the recipient field and of course if I create a new one and I feel like maybe Carla and said awful tutorial this was too long I'm a douche so this one is a douche at douche comm I don't know if is actual these actual website exists I think so but publish it we go back in our of course everything is properly saved we go back in our messages and of course here we have different information and we have the email of our douche Carl that wrote even incorrectly spelled awful so awful it's right now ok sorry guys I don't know how to write anymore anyway you notice here we created a custom meta box to store our email address and we're printing this custom meta box outside so now you know you have the knowledge to create inside your custom post type whatever information you want to save and you want to give the user the ability to save and then you can use these information and print it also as columns outside so you can completely customize the experience of your custom post type so it's pretty much it for this lesson I hope you enjoyed as usual if you did please give it a thumbs up or subscribe to my channel and if you really like my tutorial you would like to see more more video more content better content for you always free please spend a couple of minutes to take a look at my support page to check all the different ways that you can use to support me thank you again guys and as usual until the next lesson happy coding
Info
Channel: Alessandro Castellani
Views: 52,528
Rating: undefined out of 5
Keywords: tutorial, wordpress, php, developer, web development, theme, theme from scratch, help
Id: ccbImB59JXQ
Channel Id: undefined
Length: 36min 7sec (2167 seconds)
Published: Thu Dec 10 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.