Get all wordpress custom fields from a page or a post

October 10, 2009 · Print This Article

Sometimes you may need to get all custom fields from a specific post or page. How can we do that?

Just paste the following functions on the functions.php files from your theme.

Note: The function have lots of comments so it will help you to understand how it works.

function all_my_customs($id = 0){
//if we want to run this function on a page of our choosing them the next section is skipped.
//if not it grabs the ID of the current page and uses it from now on.
if ($id == 0) :
global $wp_query;
$content_array = $wp_query->get_queried_object();
$id = $content_array->ID;

//knocks the first 3 elements off the array as they are WP entries and i dont want them.
$first_array = array_slice(get_post_custom_keys($id), 3);

//first loop puts everything into an array, but its badly composed
foreach ($first_array as $key => $value) :
$second_array[$value] = get_post_meta($id, $value, FALSE);

//so the second loop puts the data into a associative array
foreach($second_array as $second_key => $second_value) :
$result[$second_key] = $second_value[0];

//and returns the array.
return $result;

Now, you can use the function like this:

$result = all_my_customs();
echo $result['my_meta_key'];

Your choice for site templates and wordpress themes


2 Responses to “Get all wordpress custom fields from a page or a post”

  1. Daniel on March 21st, 2010 7:21 pm

    Could you help me pls. with displaying list of pages with at least 3-5 custom fields ? I’m almost for 14 days searching on internet, I have only found this article but there is only one custom field:
    , I asked there for the help to add more fields but no answer , Is it hard to add and display more fields ?
    I have changed my wp-pages into girl’s portfolios so i need list of girls with the girl’s names (page title), country,province,city,age and one thumbnail image (custom field)
    Thanks a lot Daniel

  2. How To Get all WordPress custom fields from a page or a post # WordPress Tricks & Tips on March 26th, 2010 6:54 pm

    […] this code original created by LiveXP […]

Got something to say?

You must be logged in to post a comment.