Recently I was looking for a quicker method of displaying data saved in custom fields using Advanced Custom Fields. I came across a function called “get_post_custom” which pulls meta data from posts.
Returns a multidimensional array with all custom fields of a particular post or page. ~ WordPress Codex
Using this function you can loop through each field and in my case echo it. In this guide, I’m going to show you have to loop all custom fields on your single.php template.
Assuming you already have your single.php open add the following code.
On my testing setup I got the following results. You’ll notice Advanced Custom Fields creates a field with the given name and a duplicate with an underscore.
Next step is to loop through all the fields in the array using a foreach loop while also skipping fields starting with an underscore. This is the complete loop below with comments.
How get_post_custom could be used
This “get_post_custom” function is actually useful for 2 main reasons.
Looping all post meta for sites storing a lot of data can get be difficult to manage. In my case, I had a site with 10-20 filled in fields per post. Rather than having to use the standard ACF “get_field” function for each field I can echo them all at once. This also works in functions and is an easy way to target a lot of fields.
An added bonus is not having to go back and update code as fields are created, renamed or removed.
Hope this helped and let me know some of the ways you’ve used the “get_post_custom” functions.