 Good morning. Good afternoon. Good evening wherever you may be around the world my name is Jonathan and Welcome to today's online workshop As you are joining, please do let us know in the chat where you're joining us from and Maybe give me an idea of what time of day or night it is there It is about 4 30 p.m. My time And the weather today is cold and wet We are we are hitting spring in Cape Town And that means we have weird weather where it is cold one day and hot another But today is a cold and wet day So if you've never joined one of these sessions, let me introduce myself very quickly My name is Jonathan. As I've mentioned, I'm from Cape Town in South Africa I am a developer educator at automatic and I am sponsored to work with the training team The training team of the folks that create content for learn WordPress We create tutorials. We create courses. We create these online workshops creates and host these online workshops And just generally keep learn learn WordPress org going and running If you are regular of one of these Thursday sessions, it's good to see you again I want to make a special thank you to Stephen Anders who was hanging out in the waiting room when I started the session a bit early So thank you Stephen for coming back. If this is your first time, welcome And as I say, let us know in the chat where you're joining us from we have I hope I'm pronouncing this correctly But I'm guessing it's Jose from Sacramento, California. We have James from James's greetings James. I recognize from my live stream. So welcome James. We had some interesting chats about Businesses and paid plug-ins and all kinds of things in my live stream on Tuesday. So welcome James from Boston Welcome Arthur from Frankfurt. Good to see you again, Arthur Frankfurt Germany Germany is a country. I really need to travel to again. I've been there once Jose says that's seven thirty a.m. in the morning. Jose I really respect someone who joins an online workshop that early in the morning So I hope you have some coffee or a drink of choice ready And I hope that you enjoy today's session All right, while folks are joining I'm gonna I'm gonna get things going with a few announcements as I may have mentioned earlier We are doing we are talking today about the metadata API And we're gonna be diving a little bit into what that is and how it works in a second Kavya from Pune, India. Welcome. It's 8 p.m. Here 26 degrees, but it feels like 34 yikes I have been to Pune once I traveled to India a number of years ago And we went to Bangalore and we're into Pune. So I know where that is More or less And I know how warm it does get there Hi Mark from Issaquah Sharon says I trust you have recovered Sharon. Yes. Thank you for asking Sharon is asking about the fact that I a was sick a few weeks ago and then B injured my back I'm all recovered from that. I'm feeling 100% good So thank you for for asking that question Sharon. Okay, couple of announcements before we continue First of all again, welcome to everybody. This is your first time or if you've been to a few of these before you are welcome here today I don't have a co-host with me today Kind of my own fault in a way The the person who offered to co-host We're still available to co-host, but then I had to move the session and it's his last day at his current company So he's not able to make it today So please bear with me while I am monitoring the chats and admitting folks as we continue with the session If I if I have to break and do those things Please let me know if you can't see my shared screen So you should see right now an announcement slide with the title announcements across the top Please let me know if you can't see that because sometimes we have problems with the screen share and then I can just re-enable that As always in these sessions we are presenting in what's known as focus mode focus mode means I can see all of your video feeds if you enable your video But you can't see each other and that's just to prevent any instances of zoom bombing, which we have had in the past You are welcome to enable your video if you would like to you are welcome to leave it off as well It's off by default and you're welcome to leave it that way But if you feel like enabling it you can do that as well You are welcome to ask questions at any point in time. You're welcome to post them in the chat or unmute to ask questions The only thing I ask is if your question Isn't specifically related to what we're talking about at the time Please keep it for I do leave breaks Logical breaks as we continue along. So please keep it for that break or just post in the chat and I'll come back to it When we get a chance Show and it's all good. Thanks. I Should be good, but maybe keep that in mind and if you see a future workshop coming up and you want to co-host Let me know but I should be good for now. Thank you Okay Then if you would like to code along with me today, make sure you fired up your local install Be it's local WP or whatever you're using if you're like me It's it's up and running all the time But if you need to start it up start the application up anything like that, please, please do start getting that together now If I start speaking too fast, please do give me a shout pop me a message in the chat or unmute and say Jonathan slow down. I do tend to speak fast when I get excited and I'm excited about what I'm teaching or presenting So sometimes I can rattle off and rush off and leave people So please slow me down if there's anything on screen that I'm jumping away from too quickly And you want me to put it back on screen any code or anything like that or any links I'll share the links in the chat. You're welcome to ask for those things I will be checking that the chat and keeping an eye on what's happening there As always the session is being recorded and will be posted to WordPress TV afterwards And I'm just going to check that it is recording. I guess I did start the recording And then if you're looking for more WordPress tutorials courses online workshops You can find those at learn.wordpress.org And if you're looking for any specifically developer news and blog updates I can recommend checking out the new core developer blog at developer.wordpress.org slash news I'm going to share that in the chat now It's a new blog that the WordPress project launched a few months ago And it's all kinds of fun and interesting things that go on there One of the one of the more recent posts that I don't think it's live yet But I think it is coming Is Nick Diego is writing a blog article on Creating block variations, which I'm looking forward to reading So keep an eye on the WordPress developer block for all kinds of WordPress developer goodness All right Our learning outcomes today as mentioned previously. We're going to be focusing on the metadata API We're going to learn what it is and why it's useful We're going to learn how to access the metadata in the WordPress dashboard better known as custom fields We're then going to look at how to use the API to interact with the metadata how to add delete update And there was another one add update delete Oh and fetch I forgot there for a second and fetch metadata to be used on the front end or wherever And then we're going to dive very briefly into what I call the metadata wrapper functions I'll explain what those are when we get there We're not going to have time to go into all of the metadata functions This is very much an introduction to the metadata API But hopefully I'll be able to give you enough information so you can go further And start digging into the documentation Before we get going I would like to ask you to please in the chat on a scale of one to five one being you You know almost nothing about this topic. You've maybe never heard of the metadata API before To five being you you know, you are the metadata API king or queen You know everything about it. You you live and breathe metadata Functions, let me know in the chat what your knowledge level is on this topic Just so I get a feel for for where we are Myself I discovered I I thought I was a five. I'll be honest I thought I was a five before I started preparing the session And then I learned some things in the process. So I would call myself a good four at the moment There's always something new to learn It's one of the reasons I love my job so much because I get to go and learn these things and share it with you folks But I would consider myself a four on the metadata API Okay Sharon says she's a solid three. Alex is a one. Jose is two. James is a one Jim is a three. Andrew Slay says two. Mark says three Kavya says two and Peter says two. Okay, so we've got a good nice middle ground here Most folks who are developing with WordPress while making plugins and themes will at some point discover the metadata API A lot of folks who are building sites are using things like advanced custom fields which uses the metadata API So a lot of folks do know about it and do use it on a regular basis So I hope that there is something today that you discover Or if not, maybe it's just a good refresher for how all these things work All right Um, very quickly Let's just run through the requirements if you want to work along with me today Or if you're watching the recording of the session and you want to try out the code samples I'm going to be sharing today. You will need a local WordPress install You will need some kind of text editor. I use vs code You will need to be able to access your database and that's only really just to see the data being stored in the database If you have something like admin or php my admin or one of those things that will work If you don't there's also a plugin you can install called sequel buddy It currently does say on the sequel buddy website that it hasn't been tested up to the most recent version of WordPress That is because the company that acquired the plugin the company that acquired delicious brains Which is wp engine they have stopped maintaining the plugin. I'm not sure the reason for that But the plugin does still work. I still use it in these sessions So that's one you can you can check out Then you might want some post data if you have a default WordPress install that will that will install with one post If you want to create more than one post, you can use this plugin called fakerpress This is a plugin that I personally use. I'm not a fan. I'm not a friend or a promoter of this plugin I'm not I don't make any money of this. I just found that somebody recommended to me a number of years ago It's a great way for creating What's known as dummy dummy posts or dummy pages in your WordPress site And I use it quite regularly. I'm not going to be using it today. I'm just going to be manually creating some some posts But this is a good one to use if you need to just quickly create postal pages in your WordPress site And then we're going to be working in what I call a test bed file So in other words, it's a file that is separate from the WordPress install We're going to create it ourselves in the root of a WordPress install Um, but it it loads the core WordPress functionality, but not the rest of the page request And we can use that to test out WordPress functions And so the file that I'm going to use I have created this GitHub I don't know if it's just or gist gif. I don't know but there it is And what you can do is you can take this php code. It's actually a combination of php and html code You can pop it into a php file in the root of your WordPress install And then you can browse to that file and test things out So I'm going to do that now quickly. I have my learn press site setup On this local URL learn press dot test And so what I'm going to do. I'm going to open up virtual vs code virtual code vs code I'm going to browse to the folder that houses My sites I'm going to find the learn press sites and I'm going to open that up in vs code And then inside the root of the word of the learn press install the WordPress install I call it learn press whatever Where the index of php file sits and all the other sort of primary core WordPress files I'm going to simply click on the bottom here and say new file And I'm going to call it wp hyphen test dot php So that's a php file and then I'm simply going to copy this content out Of the gist or gist whatever the right pronounce I guess it would be gist because it's github not jithub So I guess it's a gist And I'm going to paste that code in there And what this does is this loads the wp load dot php file, which is a WordPress core file that Loads the database engine it loads all the sort of core WordPress functionality And we can do things like call the get option function to get the name from the database and those kind of things And that's that's what we're going to use today to test out our metadata api functions So with this file created If I browse to learn press dot test forward slash wp hyphen test dot php The first time I do this it might break. It's a weird bug. I'm okay. It hasn't broken today So there it is learn WordPress and this is hello learn press. It's getting the learn press from the database So I know this is all working. So that's the file we're going to be working in today We're not going to be building any plugins or themes or anything Because we're really just experimenting with the code as opposed to building something All right, I'm going to take a break there if anybody else is busy doing that on their side grab a sip of coffee Pause for any questions. Otherwise, we will dive into what is metadata and why we want to use it all right so if Excuse me if you browse to developer wordpress.org and you scroll down about halfway And you click on the utilize api's link under the common api's you can click on either common api's or utilize api's both will work That will take you to the common api's hand And pretty much every single api that we've been covering under the common api section is listed on this page You will see that metadata is the one two three four five six seven eighth item on the list If we click on that there is a page in the common api's handbook about metadata And so the metadata api is a simple and standardized way for retrieving and manipulating metadata of various WordPress object types Metadata for an object is represented by a simple key value pair Um objects may contain multiple metadata entries that share the same key and differ only in that value Now that's a whole bunch of words, which if you've never seen it before may or may not make sense So let's have a look in the database so that we can understand that a little bit better My local WordPress install Or my local WordPress development environment. Should I say users php my admin? So that's what I'm going to be doing to look into my database Um, here is my learn press site Here is my wp posts table. So I'm going to click on that. Actually, I'm going to click on the structure tab So that we can see the the columns in this table Um, and the column names are all listed down the left hand side. Yes. So we've got an id column Let me zoom in a little bit so it's a little bit bigger Um Oh, why is it not zooming now? Let's go. Yeah 125. There we go There is an id column a post author column a post date column Post h gmt post content post title, etc, etc, etc, etc, etc Um, and if you've never seen a database table before this is how database tables works You have columns with names and then you can store different type of data against those column names That's great, but the problem comes in if you want to be able to store additional data About a post for example. So let's say you're building a site and you're you're building a recipe blog for example and every single post is going to have Some kind of let's say mood or let's say some kind of fragrance or flavor flavor palette, let's say, I don't know much about recipe blogs as you may have noticed Um, and you want to store. Let's call it a flavor palette And you want to store this or maybe Maybe a better option is a cuisine style. So we've got different cuisines from around the world And you want to be able to store that cuisine style against the recipe blog post There isn't a field in the post table where you can store something about the cuisine style because that is very custom to the type of site you're building That's where the metadata come in come comes in Um The the description when you when you look up what metadata is if you look up like a dictionary definition for metadata metadata is essentially data about data So when we store metadata about a post or other data objects in the word per site, we store it about those posts so The other example I was thinking of when I was putting this together is let's say I'm writing a travel blog And I travel to different cities around the world And for every blog post that I write I want to be able to include a location stored against that post Um, and maybe a secondary location. So maybe I want city And I want uh state or I want country or whatever the case may be I can't store those locations against the post based on the fields in the database. So that's where I would use metadata So as an example, let's say I go to my first post here, which is the hello world post As a post idea of one I can then store in the post metadata. I can store a new record and I can say Uh, I can leave the meta ideas one. I can say the post ideas one because that's the post it belongs to I can give it a key of location and then let's say for the value. I want something like new york, whatever the case may be Sorry conspelf today And then I'll go down to the bottom here and I will hit go in my php in my admin And that is now inserted the record into the post meta table Location new york and it's tied it to that post id because I've stored the id of one there Now that's all well and good, but where would I see this information? Well, that's one of the cool things about wordpress is wordpress includes A default set of user interfaces that you can actually see and create this information You don't have to dive into the database. It's something that's been around for a while So let's pop over into my site before we get into this test bed And we go into wp admin And I'm going to go over to my posts I'm going to click on the hello world post and I'm going to enable in the block editor something called the custom fields panel So if I click on the three dots in the block editor and I click preferences panels and enable custom fields That'll ask me to show and reload the page And then when I do that there, we will see location at the bottom and there is the value stored of new york And then from this interface, I can also create additional custom fields So let's say I want to make another custom Custom field location and I want to make it new york state for example Or maybe a better option is actually let's make this one new york state for now Trust me to pick the one that has the same name as the city as the state and I can say uh into new Actually, no sorry add custom field And there we go. So now I've got location new york location new york state for example And if I view that in the database There location new york location new york state those have been added They both have they both have the post id of one The location is the key the value is the value So notice a few things number one. I always need a post id to associate the meta keys to the core data object Number two. I can have multiple keys with the same key. Sorry multiple fields Multiple meta fields with the same key. So I can have location multiple times with different values I can also have unique keys so I could change the first one to City if I wanted to and the second one to state for example, that would make it easier to manage But I am not bound by any specific structure as I am with the post table with the post table I must store Certain fields on certain sorry certain values on certain fields. I must store a title in the post title I must store the store the content in the post content So metadata is a lot more flexible But that also means you need to be more aware of what's going on Notice in the post table if I look at the structure The post author for example has to be an integer in this case. It's what that's called a big int But it has to be an integer So I can't store a string value or a boolean value or anything like that in that field that has to be an integer Whereas in the meta tables if we look at the structure The key is what's known as a var char or a variable char with a maximum limits of 255 characters So that's quite big And the meta value is something called long text Which pretty much means any type of text can go in so I can store a string I can store numbers as text. I can store URLs to images To audios I can store what's known as a serialized object So I can take an array and I can serialize it and store it in there Or I can take an object and serialize it and store it in there I can store pretty much anything that I want in there. So it has a large amount of flexibility Okay So why am I showing you all this? Well, the functionality that powers let's go back to the post that powers this meta box here This custom fields area Is the metadata api the core functions that make this possible Form part of the metadata api. So when I create here when I say add new custom field Let's actually take this one. Let's let's make this one. Let's change these. Let's go Los angeles for example And let's make this state California and if I click update there, it's calling a metadata api update function And if I click update there, it's calling the same function with certain pieces of data And now that data has been saved if I refresh this There it is displayed and if I check it in the database There the values are updated in the database So what we're going to be looking at today is those functions that underlie this functionality The other thing I wanted to mention Before we do that is that this custom fields area is known as a custom fields meta box Meaning it's working with metadata It is also possible to develop your own custom meta boxes So if you've never seen this before this is the the link into the documentation that shows you how to do that That is unfortunately outside of the scope of this tutorial I'm planning a future tutorial on how to work with meta boxes and how they can be used and the functionality of them But if you want to dive into that after the session, I do recommend going and checking that out Okay James says I was about to say I was nervous about entering and moving about in php of admin That's the beauty of doing it on a local site that doesn't matter James is you could break things and if it falls over You just reinstall WordPress But yes, I if you don't feel comfortable making those changes. I do understand And then you say I was about to ask where do those custom fields come from? Yes, so the custom fields functionality that exists in WordPress is Depending on what kind of WordPress you're using it will be enabled in different ways If you're using The block editor, which is the one that looks like this It's in the newer versions of WordPress and so I think it is WordPress version 5 Then as I showed you you click on the options dots You go to preferences panels and then enable custom fields there If you are in a classic editor environment, so I have got a classic press site set up This could either be you've got the classic editor plugin installed that is This plugin over here or you're using some other way to to get the classic editor working if you go into your post And you click on the screen options at the top You'll see custom fields is listed there if you click on that Then the custom fields will show at the bottom of the screen Okay Right any questions on how all that sort of looks and how to access it and how sort of what metadata is and why it might be useful Before we actually dive into the the metadata functionality and how it works and I leave That on the screen. No, not that one Darren's keen to go and let's dive in awesome Okay So the one thing I wanted to mention is when you enable the custom fields meta box at the bottom of a post There actually is a custom fields link at the bottom here It says custom fields can be used as extra metadata to a post that you can use in your theme with a link to Assigning custom fields. So you can go and read that as well. If you would like I'll actually show that in the chat And then we can do some we can do some diving So what I'm going to do now is I'm going to create a second post And I'm going to just say something simple like howdy And this is my post And then I'm going to Publish this post so that it gets an id. I could have saved a draft as well. That would have worked If you there's a couple of ways you can get your post id the one way is usually the post id is the The numeric value in the query string. So post equals seven. So seven is the id. That's one way you can do it The other way you can do it is if you pop into your database and you go to your post table And you search for or look for your post Let me just sorry Let me just move that out the way It will be the one that is that has got the post title with the status of publish That will be the post id. So there you just see it's id seven there But I find the easiest way to do is to get it from where is it now get it from the url There's always a post value there and there is id seven So i'm going to copy that into my memory now so that I want that id seven i'm then going to hop on over to my test bit And i'm going to remove the echo hello side name bit And i'm going to remove the get option bit And the first piece of code that I want to introduce you to Is the add metadata function So to find that i'm going to go back to the developer documentation I'm going to click on the code reference link which takes me to the list of all the functions and classes And i'm going to search for add metadata And here is the documentation page on add metadata So the great thing about the WordPress documentation is it gives you the function signature In other words what the function looks like and what parameters it accepts It gives you the list of parameters And tells you what data will be returned from the function Shows you the source code of where it exists And then any user contributed notes that exist underneath that Which often will have example code that you can use So the add metadata function has Four required parameters one two three four The first one is the meta type so the type can be post Comment term or user And that is because if you have a look at your database You will see that WordPress database has metadata Tables for those four data objects so posts has the post metadata table Terms has the term metadata terms would be your categories or your tags Users have user meta And comments have comment meta So if ever you're working with any one of those four data objects And you need to store or retrieve additional data on them You can create meta for them and it all works in the same way Let me close that and go back here So the first one is the object The second one is the object ID in this case the post ID and our post ID is ID seven The next one is the key So that's the value you want to store as the key for the metadata And the fourth one is the value so that's the value you want to store So to be able to do what we did in the custom fields programmatically on this post We would simply do the following we would say add metadata And then we would pass in post We would need to pass in the ID which we said for our case was ID seven It'll be whatever your post ID is on your site Then the key I'm going to work with the same key we worked with earlier which is location And then the value so this case I'm going to go with some more california places And I'm going to go with san diego And then the add metadata function if we look at what it returns it returns either The meta ID so in other words Let me go back to the post meta field this ID value for the record in the metadata Or it returns false if something goes wrong So if you've passed something incorrectly through or you can't add meta data for that post ID it will return false So a good thing to do with this information is to do something like this and to say Meta ID equals add metadata Now More strict software developers might complain about the fact that it can return either an integer or a boolean That's an argument I Agree with in some respects and disagree with others. It's the way it is. So I've learned to work with it But what you can do now is you can do something like this. You can say if metadata ID Meaning if a valid value is returned, so if we get an ID one back Then we can say something like echo meta data record added with ID and then the meta ID And then we can say else, which means if it's a if if there's not a valid value or it returns false in other words, something's gone wrong We can say echo error Occurred or something like that Um, because this is just a test. It doesn't matter too much what we do But that is what your code looks like. So it's add metadata type add in the sorry pass in the object type the object ID the metadata key the metadata value Okay, I'm going to copy this code out and pop it in the chat James. I saw your comment there I will get to it in a second, but let's see what this does on the front end So let's go back to our have I got the test bed open? No, I don't think I do. So let's close down some tabs here Let's close that. Let's leave that on that there Let's close down that one and let's open up the test bed again There it is And now if I hit enter it's going to run that code And there it is metadata record added with ID of nine. So that sounds like everything went well If I pop on over to the post meta table and refresh it There it is ID nine It's created a metadata idea on post ID seven with location San Diego And we can verify that by refreshing this post either just hitting refresh in the browser or hitting enter on the address bar And we should see there it is there. We've got location and San Diego in the in the customs fields panel. So we know that's worked Okay, James says my brain is already thinking this metadata custom field option helps with the taxonomy of a post, right? Good for organizing and maybe even SEO perhaps so get say a government site with large archive Jose says you can use metafield to store a term of a taxonomy on the post But this won't create the relationship between the post and the taxonomy Then if you need to query you won't be able to use the tax query and you'll need to use the meta query instead and that's exactly correct So if you want to use things for for taxonomies of posts use the built-in categories and tags I'm planning on doing a session on on the taxonomies in WordPress one day soon But the short of it is the categories Trying to remember now categories can have parent categories, but tags caught Or something along those lines. There is a difference between two. I can't remember what I've had now But if you want to categorize things rather use categories and or tags those are your taxonomies in WordPress What I tend to use metadata for is when it's just I need to store additional data on something so A good example would be a membership site You might want to use your users As your members and you might need to store their addresses or their contact details where they're located Possibly what courses they've passed or whatever the case may be that's where you might use metadata All right Any questions on adding metadata programmatically? Private data is a good option. Yes, just note though that your metadata fields are not What's the word I'm looking for? I say hashed hashed is the wrong word, but they're not What is the word they're stored in plain text So if you want it to be really private, you don't want somebody to hack it. You might need to do some kind of hashing yourself They are stored in plain text. You just be aware of that Okay so Who can guess What the function would be to up if add metadata allows us to add metadata Who can guess what the function would be to allow us to update metadata? Anybody See if see if anybody wants to take a guess in the chat fast fastest fingers first Okay, it says update metadata it you're exactly correct So one of the things I love about WordPress is things are fairly straightforward If you know where to start and you know what can go from there So update metadata is the function to update metadata Um I say says WordPress developers are very semantic about this 100 correct And it takes exactly the same parameters So it requires the meta type the object that we're updating It requires the object ID. It requires the key and it requires the string It also has an additional optional value called previous value or private value And this if you specify it will only update the existing metadata metadata entry with this value Otherwise update all the entries now the reason this exists is because as I mentioned earlier if we look at the metadata for post id 1 You can have multiple metadata key value pairs using the same key So you could store location four or five times And then when you call update you need to say to it Well, I only want to update for example the one that is location Los Angeles not the one that is location california And then it will only update the one that's location Los Angeles if you pass in that previous value For our purposes we can keep it super simple. I want to update the location from San Diego to something else So in my code I can just say Update metadata. It's the same post the same id the same key this time. I'm going to go with san francisco for example Uh, so san francisco. There we go um You will notice that Let's go back to the function It returns the same results. So either the new meta id field if it didn't exist and therefore was added True on a successful update or false on failure. So this is an interesting thing to note It is possible and I'm going to do this in a second. In fact, let me let me do this first. Let me show you this I'm going to call Meta id equals update metadata post seven location And I'm going to actually go I'm not going to go location. I'm going to go city Actually, no, let's go state and I'm going to say state is california So this is using update metadata not add metadata um I'm going to do that and then I'm going to run this code So I'll get back to this in a second if you want to see it But there we go. I've called update But I didn't I didn't say to it updates an existing one with state because state if you remember we haven't added yet against this post up WordPress will check Is does they is there a meta key with state and if it doesn't it'll actually then go and add it for you So this is an interesting an interesting one because you'll often see in plug-in or theme code folks will receive some data from the user somewhere And and and metadata is supposed to be stored and then they'll just call updates Because updates will either update an existing one with location is the key or all of them if there's multiple If it doesn't exist, it will go ahead and add it What I prefer to do if I know that I'm expecting certain types of metadata Is I will have some kind of plug-in Initialization function that fires when the plug-in is first installed Or some theme initialization function when the theme is first installed And I will add those metadata keys with an empty value to begin with against the post Or when the post is if I'm expecting the post the first time I will check as it's been added and then I will add it You don't have to do it that way. It is nice that the update does it for you So if you just call updates and it doesn't exist that will add it for you It really depends on your personal preference there But calling updates and passing in a key and a value that doesn't exist against that post id will create the record for you It will obviously also update the record. So let's say I change location to san francisco like I wanted to Let's go back to the code. So we'll change this to location and we'll say san fran Cisco If I then run this and let's change this back to updated Then it will specifically it should just update id 9 So let's test that All right, it's updated with id 1 Oh, hang on. What have I done wrong here? Let's have a look I've done something wrong It has updated it correctly, but it's passed in a pass back of one for some reason. I don't know if I've done something wrong in my code somewhere Um, oh wait, wait, wait. I know what I've done wrong If it's if it's a successful update that will return true Not the id And if you if you if you render a true boolean in html it renders a 1 so that's what the difference is there So be aware of that change when you're updating something It'll only give you the id if the key didn't exist It'll pass true if it was a successful update and false if there was a failure And so you need to check against those options when you're working with this code If all of that doesn't matter to you and you just want to make sure that it was added Then you can do something like this and you can say if not met the id because True would pass as false and a valid one or two or nine or whatever a number would be a true value So you would say if not met id Then you can echo an error occurred And then otherwise you can say The metadata record was updated Or at least you can store that it was updated, but you can't necessarily rely on the id You could do a check You could do something like this. You could say I'm diving a bit of a tangent. Yeah, but bear with me. You could say if Is numeric? I think it is Yes, you can call the is numeric function And then you can check that on the id so on the meta id So now if it's a numeric that means it was added Record added Hang on I've left out something there Otherwise you will say it has been Updated Okay, and this is one of the reasons why some developers prefer it when a function just returns one type of variable So not an integer or a true or a false because then you don't have to do all this kind of checking if you want to Return some information to the user Okay, I'm gonna I'm going to copy this out So that you can see that code if you want to I see there was a comment in the chat So there we go Elliot says why didn't all location keys get updated? That's a good question So let's have a look at specifically The location keys that we have let me refresh this. So we've got three location keys Two of them are tied to id one And because I passed in post id seven it ignored those There is only one location key here tied to id seven. The other one is stored as state So it only found that one However, that brings up a good point. Let's add a new location just to show you what that looks like I'm going to do it manually in the data And then I'm going to show you What would happen? So let's add another post id seven Let's add another location meta key and let's say the location was downtown or something. I don't know san francisco But I've heard the word downtown related to san francisco So let's saw that as a secondary location And now let's look at what the data is So for post id seven we've got location san francisco. We've got location downtown If I want to only update location san francisco, I need to pass in san francisco is the previous value If I just say update post id seven location to I don't know random other city los angeles in california los san and girlies Now it's going to update all of them. Let's test that Okay, it's been updated Let's refresh the data and there you go Both the first one and the second one have been updated to los angeles So if you know you're storing more than one metadata key with the same key value Make sure you pass in the previous value so it updates the correct field Okay Idiot says what if there were multiple location keys and then he says you're ahead of me But I'm glad you asked idiot because it allowed me to go down that path and it's important because it comes up just now Okay So that's adding and updating The other one we want to be able to do is we want to be able to fetch the data before we delete it So this is where we want to fetch it for a front end somewhere Um, I'm not going to break but if you have questions you're welcome to give them in the chat I want to make sure we cover everything today so If it does anybody want to guess if you can add an update metadata, what would the function be to get metadata? The answer is quite simply get metadata Um, and this and this will apply through all of WordPress. Generally, you will see things like add Updates and get and then the type of data that you're receiving So that function is called get metadata Um, it also has specific parameters again. The post type is the first required parameter um The object id is the second parameter and the meta key is the third parameter And then there's a single parameter Which if it's true return only the first value of the meta key Otherwise if if if you don't specify it so it says the parameter has no effect if meta key is not specified Meta key you'll notice is optional So let's go through the different options here based on the required parameters and the optional parameters starting with just the required parameters. So I'm going to just call this data And I'm going to say get metadata post id 7. That's all I want to do I just want to get all the metadata stored on post id 7 And then I'm going to use a php function called print r Um With some html tags that look like this pre-re tags pre-formatted tags This is a great way of formatting a print r function call When you want to have a look at data that you don't know what it's going to be whether it's going to be An array or a string or anything like that um When I first started working in php. I use this a lot Okay, so that's it. So data equals get the metadata for post id 7 And then echo that out on screen. So that's the code we're going to use Let me just pop that in the chat so you all can see that I saw your question about serialized strings. I'll get to that in a second edit So let's see what that does Okay, I'll have to make this a little bit bigger so that we can see it because it doesn't make it I don't know why am I oh, I'm using okay. Sorry folks. I'm using command in the scroll button, but it's command plus Make it 150. There we go So notice that there are quite a few meta keys stored on this post The first one is the edit lock. You'll notice it has an underscore in front of it Those are what are called hidden custom fields or hidden meta keys And you will notice that they don't appear if I go to the howdy field They don't appear in the custom fields meta box. That's because they have that underscore in front So that's another way you can James getting back to your question earlier about private data If you store meta keys with an underscore in front of the key name, it doesn't show up in the custom fields Again, hash it or store it in a secure way if you need it to be secure, but it's a way of sort of hiding that data from the average user WordPress uses this for certain things. So in this case the edit lock Is a field that is set when somebody is working on a post And it's how WordPress knows that another user is using a post So if another user logs into the site, it's how WordPress knows to give that a little message So hey so and so user with such and such ideas working on this post I'm not sure what enclose me does I'm sure if I went and searched it in the documentation, I would find it, but there it is There's also the edit last meta key that's stored And then here are our custom meta keys that we created So the first one is location And you'll see it fetches the two values in an array So it gets the location key even though they are look if you look at the database There are two separate records in the database. It returns them as one array And then it returns state as another meta key and then an array as well And the first item is the item in that value And the reason it does this is because you can store multiple Meta keys sorry meta values on the same key. That's why it returns an array So if you just first of all if you just want to get back a specific key You would pass in the key in this get meta data function So let's just go for location for this one And let's refresh that Okay, and there is location Now the reason it's returning an array is not because they are two that is the default it always returns an array Let me show you what I mean if we go and look for state And we refresh that code It returns california in an array the first item in the array is california Even though it's just one record in the database The reason it does that is because there could be multiple and the wordpress code base doesn't know whether there's multiple keys or not So it just always returns an array But let's go back to the location one If I just want to get one value Then I can return single Sorry, I can pass in a value for single and I can say true And if I now call this code It'll just return the first one it finds just as a single piece of text not in an array So if you are working with now the the recommendation is Unless you really want to have multiple values on the same key, which is generally not a good idea because then you have to work through the array Generally, you would store just location And then maybe city and then maybe state and then different values on those But if you want to get those back as a single value, you must always pass True as that single parameter So it becomes when you're working with metadata when you're fetching metadata Passing true is that fourth parameter becomes something that you that you do by default, especially if you want to display it on the front end Eliot says I've seen serialized strings added to a single key. Is that an accepted method? So let's talk about that very quickly. This wasn't on my plan for today, but it's a good thing to cover I can take an array of data or an object data object So let's create a very simple array. So we'll say array equals and I'm old school. So I use the old school array method And let's say we're storing an array of values Um, I don't know days of the week maybe so we'll say Monday Tuesday so on and so forth I'm just going to store money to Wednesday for now And then I'm going to say Meta id equals and I'm going to cheat by using update metadata because it will add for me update metadata I want to store it on the post. I want to store it on post id seven I'm going to call it uh days of the week just dw And then I'm going to pass in just that array as is. I'm going to do nothing else to the array So I'm not doing any kind of special formatting or anything else and then I'm just going to say I'm just going to keep it simple. I don't expect it to fail. So I'm going to echo it done finished So I want to show you what this does when I run this code So an array if you've never seen an array in programming before it's a collection of variables If I run this code it's done Let's go and see what's sitting in the metadata So by default if you pass an array to a meta value It will do what is known as serialization. So it takes the array or the object It serializes it into a string and stores it as what's known as a serialized string This is a this is a common thing in I can't get this thing to stay because I'll just drag it there This is a common thing in programming. It could take an object on an array and convert it into a string version Which is known as a serialized string And then when you fetch this data, so let's do the fetch I'm just going to comment this out for now I want to show you what happens So let's say data equals get metadata And it was post and it was id 7 and the key was days of the week And then let's I'm actually just going to grab from my test code here the print our stuff It's down here somewhere. Here we go. It's just easier than typing it all out again There we go print our data Show you what happens There we go. Notice how it's an array within an array So if I were to pass in single I would get the original array back I wouldn't get a single value. I would then have to traverse through that array if I wanted a specific day So it is possible to do that You can store serialized strings if you want to store data objects like that You just need to remember when you get them back They're going to be an array with an array even if you pass single if I change this to single Then I'll just get the array on its own Um, no, it's not single true True to single So let's do that But I still get the original array So it takes whatever the original data was that was stored in this case an array and returns that original data I can't just get the first value from there. I would then have to use some array functionality In php to get the first item if that's what I wanted Okay James says if we wanted to target multiple cities, okay, I think I've covered that Idiot says void up with empty bag. That's another option There's many ways to to get the data out there. Okay And then finally I'm not going to ask you to guess I think we all know what the delete metadata function is going to be It is going to be delete metadata. So let's have a look at that Delete metadata has some additional options on it as well So the first one is again string type in other words post Comment term user object ID again is required meta key is required Meta value is optional. I'm not going to code this But meta value is optional because maybe I want to delete all the keys all the values against that key I can just pass in the key and it'll delete them all So if I just say delete metadata post seven location, it'll delete both of those If I specify the value as for example, Los Angeles In this case, it'll be both anyway because we've changed it But if this one was still San Diego or whatever it was it would just delete the Los Angeles one But then you also have an option for delete all So if this is true delete matching metadata entries for all objects ignoring the specified object ID I've never had to use that optional Parameter, but it does exist So you can you can probably pass in null for the object ID Call the location meta key and say delete all the delete all the location meta keys and values against posts across the site Okay, I'm not going to code that now because I think we all know what that's going to look like I wanted to stop and just check if there are any questions around all of that Before I move on to A very quick note on the metadata wrapper functions Because we have five minutes left Okay, there don't seem to be any questions. So let's dive straight into that If you have been working with WordPress for a while You will know that there are what are known as metadata wrapper functions or at least that's what I call them Where you can add metadata for specific object types So for example for posts You have an add post meta update post meta Get post meta and delete post meta functions You'll notice that those parameters are post ID key value And then the same additional values. So for add it's unique for update. There'll be previous value for delete, etc, etc These wrapper functions essentially call the add update get and delete functions that we just discussed Underneath but it's a shorter way of working with specific object types So if you're working with posts or pages or any other custom post type and you want to work with metadata there You can just use the add post update post get post and delete post meta functions If you're working with Comments same story. You can go add comment meta On spell comment meta again add comment meta update comment meta get comment meta delete meta same for users Add user meta update user meta get users. It's all it's all the same throughout the whole WordPress WordPress So that's great because then you are making your life easier You're writing shorter code because you can leave out that object name If you look at the number of letters add post meta And add metadata are about the same. So that's about the same But you don't have to worry about what type you're storing against and so, you know, that's what you're working with at every single time There's nothing wrong with using the core add metadata functionality Um, I just prefer to use the ones that are the wrappers because I don't know I'm specifically working with that type And I now have to worry about making a mistake in that bit of code Okay That is my bit for today. Does anybody have any other questions about the metadata API? Is there anything that they felt that they wanted to learn today that I didn't cover? Or anything else before we before we wrap up for today Okay, Jose says please cover the meta field creation. I assume you mean the meta boxes Which yes, I definitely am going to cover that so to I'm not going to do it soon But to give an idea I I'm I'm going to share this with you very quickly Um There's two there's two things that I want to cover under that topic. I just want to find the the post Oh wait, I'm searching in the wrong place. Sorry folks uh So the fun the fun thing about these sessions is I have to first cover the metadata API before I can talk about meta boxes So this is one of those we do this one now and then we do the other one another time I'm not going to find the post that I want now am I Hang on. Let me let me try and search what I'm searching for is there is a there is a post on the training team blog Wait, hang on That covers all the topics that I'm busy working through Here we go So this post is basically covering all of the topics that I'm working through at the moment You will see that one of the sections if we scroll down here One of the sections section eight is an introduction to all the common WordPress APIs, which is what I'm currently working through When I do I'm going to come back to WordPress plugins And probably in the introduction to WordPress plugins. I'm you see there. There's a section on using post meta So when I get round to that topic, then I will do a session on that So it is coming I just I need to get through a whole bunch of other things as well. So I'm doing the introduction I'm doing this whole section first so far. We've done images dashboard widgets the database We haven't done the file system yet. We did global variables a couple of weeks ago Today is metadata Next I'm probably going to be doing the HTTP API Options and settings after that. Then we'll need to do rewrite shortcode and transients And then when I finished all of that, then I'll probably swing back and we'll start looking at probably plugins or themes So that content is coming bear with me And do keep an eye on this post because as I update as I create new talk tutorials, I update the links there Awesome, that is my bit for today. I want to thank you everybody for joining me Please do dive into the documentation about the metadata API about creating meta boxes about how this all works If you have only ever used custom fields in the WordPress post edit screen or something like advanced custom fields I recommend understanding the underlying functionality the main reason I recommend that is because If you're working on a site that had that requires maybe one or two custom fields It's often a lot easier and a lot less overhead on your site To code it yourself in a plugin as you saw it's fairly simple to add and update meta fields and get the data from the meta field As opposed to installing a thing like toolset types or advanced custom fields. I'm not saying don't use those plugins They are very useful plugins But I like to whenever I'm looking at a project I like to go well How many meta fields am I going to use and how much overhead will I be adding if I install a plugin that allows me to do everything But I'm just doing one or two things. So it's always good to understand how the underlying functionality works Even if you never use it, it's just good to know what it does Awesome. Thank you all for joining me. Um, it has been it has been as always amazing to interact with you all Have a great rest of your thursday and the rest of your week and I'll see you all next week. Bye. Bye