WordPress tip: Get all custom fields from a page or a post

October 2, 2009 at 2:46 pm

Sometimes you may need to get all custom fields from a specific post or page. Thanks to Paul, who contributed to WpRecipes, for sharing a function that do the job.

Paste the following functions on the functions.pjp files from your theme. 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;
    endif;   

    //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];
            endforeach;
     endforeach;
   
    //and returns the array.
    return $result;
}

Once done, you can use the function like this:

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

This recipe has been submitted by Paul, thanks for him! If you have WordPress knowledges, feel free to share it with us!