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.


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

Also available:


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;

Posted in Custom Fields