WordPress Custom Fields
by Joey Hernandez on Tuesday, April 20th, 2010
I’ve always seen the “Custom Fields” field below the HTML editor in WordPress, but never knew how to use it… Turns out it’s actually a useful feature that allows a writer to display (or not display) specific content per page. I’ve found it useful for marketing blurbs that you want to put on various pages on a site (I’m sure there are other good uses too).
So I recently updated the site for my side business: Gorirra Consulting.
In my initial mockup, I had that “ribbon” that displayed some text… it’s pretty good for marketing foo foo text. However, I didn’t want to have to add too much extra html in the actual posts (div’s and span’s).
Coincidentally, I’ve been reading “Digging Into WordPress” and they mention custom fields.
It’s basically like creating a variable (string) for the page… if the variable isn’t set, the page won’t perform the action.
So here’s the code that you’d put in the php:
<?php $message=get_post_meta($post->ID, "displayRibbon", true);
if (get_post_meta($post->ID, "displayRibbon", true)) {
echo ("<div id=\"ribbon\">
<span class=\"txt\">$message</span></div>");
} ?>
Let’s break it down, shall we?
<?php $message=get_post_meta($post->ID, "displayRibbon", true);
The get_post_meta function will return the contents of the variable (displayRibbon). It’ll return FALSE if the custom field is not set. So this basically sets the string value of “displayRibbon” into $message.
if (get_post_meta($post->ID, "displayRibbon", true)) {
Your standard IF statement… this time I’m using the get_post_meta function to simply check if the displayRibbon is set. If TRUE, then…
echo ("<div id=\"ribbon\">
<span class=\"txt\">$message</span></div>");
Write this div code that displays the message variable.
Now that the code is broken down, this is what the custom field will look like in your WordPress page:
Overall, custom fields are a great way to simplify your post/page updating process… the less div’s and span’s that you have to write, the better… let the code figure it all out…


No Comments