The base_get_all_custom_fields() function will run a database query to get all custom fields attached to the current page, post or post type and store them in an array. This is a lean way to retrieve all custom fields in one database query.
Add the function to a theme
Open up your themes’ functions.php file. If you don’t have one, create it. Add the following PHP function to the file:
/**
* Get all custom fields attached to a page
*/
if ( !function_exists('base_get_all_custom_fields') ) {
function base_get_all_custom_fields()
{
global $post;
$custom_fields = get_post_custom($post->ID);
$hidden_field = '_';
foreach( $custom_fields as $key => $value ){
if( !empty($value) ) {
$pos = strpos($key, $hidden_field);
if( $pos !== false && $pos == 0 ) {
unset($custom_fields[$key]);
}
}
}
return $custom_fields;
}
}
Use the function in a theme template
Open up a WordPress theme template file such as page.php and add the following, replacing my_custom_field_value with the name of the custom field you want to display:
// Get all custom fields attached to this post and store them in an array
$custom_fields = base_get_all_custom_fields();
if( !empty($custom_fields) ) {
print_r($custom_fields);
}
?>
That’s it, I hope this helps someone out there!