In the first article of the WordPress Custom Fields series we looked at what fields are and how to create and display them. We also looked at how to check and display a field only if it has a value. Assuming that you have read that article and are more or less familiar with the basics of using custom fields, let's now look at doing more fun things with custom fields.
To quickly recap the idea of custom fields, they are made of two parts: the key and the value. You define a key once, which is usually universal to your WordPress setup, and the value can be defined on a per post basis. You can also set multiple values to a key in a single post.
WordPress Custom Field Trick #1: Display Multiple Values of Same Key
Suppose you are creating a page to display your restaurant menu. A page displaying the menu could have multiple deserts. If your key is called Desert_Type
, you can declare multiple values to it. For example, you may have Chocolate Truffle, Orange Cake, and Pudding on the menu. Add the following in your WordPress Post as custom field entries:
You would display a single value like this:
To manage the same thing for multiple values, you would need to retrieve the value of Desert_Type
in a loop:
This is how the values will be displayed. The reason why they are being displayed as a list is because they have been placed in an unordered list. You can now modify the CSS file for the theme you are using to display it in a more fancy manner.
For you non-programmers, what we have done here is assign the value of the keyDesert_Type
to the variable $desert
. We then display the value of $desert
in a list. We have also put the line that calls the value of $desert
in a loop to display each value of $desert
.
The final output will look something like this in your Web browser:
WordPress Custom Field Trick #2: Make Content Dynamically Context Sensitive
We just looked at how to display multiple values of the same key. You might also want to display different content depending upon the value of the key. This is how you can make your content dynamically context sensitive. This is a great way to display relative ads on your blog. In this example, we'll display some text along with a link. The text will differ for meat eaters, vegans, and health freaks.
The above code is pretty self explanatory. We are asking WordPress to display the related link and text depending upon the value of the key Meal_Type
. You can also add images to this if you like. Here's what your final output will look like. Note the hyperlink added at the bottom of the post.