The function below will store a distinct list of all custom fields for the list of posts/pages/custom posts that is passed to it in the keys of the array $customfields
. The array values are the number of posts with the corresponding field. In the example, custom fields added by plugins are excluded ($value[0] != '_';
) but these could easily be added back in.
function all_custom_fields($allposts) {
foreach ( $allposts as $post ) : setup_postdata($post);
$post_id = $post->ID;
$fields = get_post_custom_keys($post_id); // all keys for post as values of array
if ($fields) {
foreach ($fields as $key => $value) {
if ($value[0] != '_') { // exclude where added by plugin
$customfields[$value] = isset($customfields[$value]) ? $customfields[$value] + 1 : 1;
}
}
}
endforeach; wp_reset_postdata();
return $customfields;
}
// example - all post types, whether published or not
$args = array(
'post_status' => array('publish','draft','pending','future'),
'post_type' => 'any',
'posts_per_page' => -1,
);
$allposts = get_posts($args);
$customfields = all_custom_fields($allposts);