WEB170 » Using Custom Fields in Your WordPress Site
Have you ever felt like there must be some way of setting pages or postings to behave in a certain way given a key and a value? You have?! Than you should totally check out how to use Custom Fields in your WordPress Site!
What are Custom Fields?
Let me start off by explaining what custom fields actually are and what they can do… WordPress defines the use of Custom Fields as having the ability to allow post authors to assign meta-data to a post.
This meta-data is handled with key/value pairs:
- The key is the name of the meta-data element.
- The value is the information that will appear in the meta-data list on each individual post that the information is associated with.
In the above case:
- The Key is set to “banner”
- The Value is set to “http://www.rehabwashington.com/WP2015R//wp-content/uploads/2010/06/female-warehouse-worker-cropped.jpg“
How do I use Custom Fields?
So… what does this mean? Let’s take a look a closer look at the example above…
Let’s say that I have pages in a website that have or do not have spotlight images. So, I want to write a conditional that says…
If there is a spotlight image to display on this page… display the spotlight that I have assigned to this page:
So… what does the code look like?
Basically we need to write a conditional that checks to see if we have used a key of “banner” on this page. And, if there is write the markup for the spotlight with the value of the key of banner written into the source attribute of the image tag :
Step One: Create a Custom Field
Let’s go ahead and create a custom field of our very own.
Here’s what I want to do… I want to set up a custom field to put a quote in my sidebar on my pages. But, I only want to put the quote in the sidebar if one exists. And, if it does exist… get the value.
Let’s go to our “About” page and set up a custom field…
First, if you don’t see your custom fields, got to your screen options and show them on your screen:
Once you have turned them on… 1) fill in the name filed, 2) fill in the value field and 3) click add custom field:
Step Two: Use Your Custom Field
Let’s write out what I want to do in psudo code:
- If the custom filed of “Quote” exists…
- Write the markup to display my quote.
- Place the custom filed value of the key of “Quote” in an element
1) If the custom filed of “Quote” exists:
Here is where we are using a simple “if” statement to ask is the key of “Quote” exists using the Get Post Meta function.
2) Write the markup to display my quote:
Here is where I am just writing a dummy block quote to test my conditional.
If I go and take a look, I should see it only on the page that has the custom field of “Quote”:
3) Place the custom filed value of the key of “Quote” in an element:
After I give my it a bit of style, my blockquote looks nice: