Mr Portman

School website critiques, articles on education and some random cod

Accessing custom field data in WordPress

Date: 31st January, 2010

Custom fields add extra functionality to WordPress. They allow you to add a field and a value, then use that information for whatever you want. I’ve recently been working on a project which lists courses which can last several months, and I wanted to use custom fields to create Begin and End dates.

Despite the praise custom fields are getting, I didn’t think they were that easy to add to a post – for this particular project I was being very mindful of making things as simple for the client as possible. However, I found a solution for that in a plugin called More Fields, reviewed elsewhere on this site.

Anyway, another problem with custom fields is that they are stored as a string. This I found to be a real pain. Let’s say I save a Begin date of 22/02/2010 and another of 16/04/2010.  If I want to compare these using the standard WP syntax for custom fields:

query_posts(‘meta_key=miles&meta_compare=<=&meta_value=22′);

…it doesnt work! Why? Because it’s a string. That means 22/02/2010 is higher than 16/04/2010! That’s a pity, because it meant I couldn’t use the meta_compare within the query_posts tag. Instead, I had to extract the custom fields with the WP loop, as so:

$beginDate = get_post_meta($post->ID, “Begins”, true);
$endDate = get_post_meta($post->ID, “Ends”, true);

$postMonths = get_months($beginDate, $endDate);

The above code shows the Begins and Ends custom fields being extracted into variables before being passed into a function I talk about elsewhere.

August 2010

July 2010

June 2010

May 2010

April 2010

February 2010

January 2010

December 2009

November 2009

October 2009

September 2009