Functions to Fetch Custom Field Values

I find with custom post types you end up fetching custom values a lot so I wrote a set of functions to make the process easier and more efficient. This code can be included in your functions.php file. Personally I like to bring it in with an include to keep my code tidy.

You can just pass your custom field name to custom_field() or get_custom_field to have the value retrieved. It has a couple ways to format data that I find are common custom fields: dates saved as Unix timestamps, text blocks, html code, and Google Maps embed codes. And if your value is a date, you can also pass a date format as your third argument, or get the default of F j, Y.


Code Snippet:

custom_field('field name', 'format', 'date format');

Also available:

Code Snippet:


Field = required
Format = optional
Date Format = optional

Code Snippet:

/* Functions for processing custom fields */
function get_custom_field($field, $format = '', $date_format = 'F j, Y')
        $fetch = $field;
        $fetch = get_post_custom_values($field);
        $fetch = $fetch&#91;0&#93;;

        // Date
        if ($format == 'date' & $fetch !='') $fetch = format_date($fetch, $date_format);

        // Text Block
        elseif ($format == 'text_block') $fetch = wpautop($fetch);

        // HTML
        elseif ($format == 'html') $fetch = html_entity_decode($fetch);

        // Google Map
        elseif ($format == 'google_map') $fetch = display_google_map($fetch);

        return $fetch;

function custom_field($field, $format = '', $date_format = 'F j, Y')
        echo get_custom_field($field, $format, $date_format);

function format_date($date, $date_format)
        $date = date($date_format, $date);
        return $date;

function display_google_map($code)
        $code = html_entity_decode($code);
        // Remove the info bubble. Usually desirable, but use the html format if unwanted.
        $code = str_replace("output=embed", "output=embed&iwloc=near", $code);
        return $code;

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!