Adding custom fields with multiple values to a WordPress post

The problem

I was working to create a system that allowed users to submit a Gravity Form entry with multiple file attachments that would create a post on the front end, printing those attachments. GF and the wonderful Gravity Forms + Custom Post Types plugin makes it easy to map a form field to a custom meta field (new or existing) – however I ran into a snag when trying to display multiple file uploads.  Simply echoing get_post_meta was just returning one of the meta field values, not each value.

Multiple custom field values with same key

The answer

Create a simple loop that stores each of the meta values to a variable, then loop through each echoing out the file links. This loop will need to be added to the post content either via theme template, filtering the_content(), and adding it onto a hook.  With this particular project using Genesis, I added it to the genesis_entry_content hook.


<?php $bulletin_files = get_post_meta( get_the_ID(), ‘bulletin_file_upload’ );
if ( $bulletin_files ) : ?>
<?php foreach( $bulletin_files as $url ) { ?>
<li><a href="<?php echo $url; ?>">
<?php echo basename($url ); ?>
<?php } ?>
<?php endif; ?>

Custom fields looped

A really cool function used in the snippet above is basename(). It’s a simple php function that takes a string for a file path (in this case a url) and just grabs that filename at the end of the string.  Pretty cool and way simpler than some regex solution.