Getting Started with WordPress Custom Fields | WebReference | 2 | WebReference

Getting Started with WordPress Custom Fields | WebReference | 2


Using the Custom Fields Feature in WordPress [con't]

For those who are not familiar with PHP, this line prints the value of the variable Desert_Type. Launch you web browser and go to the URL of the post you just created. Look on the page, and you will find the text Chocolate Pudding somewhere in there. Voila! You just created and called your first custom field in WordPress. To do a quick recap, the part of the line of code you just entered that you need to learn by heart is get_post_meta($post->ID, "Desert_Type", true). You will be making this type of a call in every custom field customization. Now move this line of code to another section of the single.php file and it will appear in another section. Play around with this line for a bit till you figure out which part of thesingle.php file addresses which section of the page.

In all likelihood you will be creating a multi page website. In such cases there may be cases wherein a particular custom field has not been declared. Wrapping up this bit of code into a conditional loop allows you to make sure this does not create a problem. For example, in the case of the restaurant website if you have a buffet menu where you are calling the Desert_Type custom field there may be a scenario where there is not desert included. You can use the following bit of conditional code to check and replace the custom text with a standard one. What we are doing here is that we are using a bit of PHP to first check if the Desert_Type field has a value. If not, we direct the page to display the text No desert included..

Figure 3: Page to Display the Text No desert included.

This is a rather simple example of the Custom Fields feature in WordPress. It is, nonetheless, an example that will help you get a hang of things. I suggest you play around with what you have learned so far a bit more, on a few more pages, before you move on. In the next article we will look at doing more creative things with the custom field feature in WordPress.

More Reading on WordPress Custom Fields

In this tutorial we learned to use the get_post_meta function of WordPress. You can read up a bit more about this function at the WordPress Codex website. Reading up about some of the options of this function will help you pick up the custom fields feature a bit faster.