, LLC.

Get All Custom Fields Attached to a Post, Page or Post  Type

The base_get_all_custom_fields() function will run a data­base query to get all cus­tom fields attached to the cur­rent 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 ) {
		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) ) {

That’s it, I hope this helps someone out there!

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 16 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.