Are you looking for a way to fetch custom field values from your custom post types? There can multiple ways to format the data in custom fields, we have created a quick code snippet that you can use to fetch custom field values in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
/* 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[0];
// 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;
}
Usage:
custom_field('field name', 'format', 'date format');
Also available:
get_custom_field($args);
Field = required
Format = optional
Date Format = optional
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 7 best VPN services for WordPress users and how to easily create a multilingual WordPress website.
Comments Leave a Reply