I had a situation where values were being stored in a post as a particular custom field. Ordinarily, coding the value of the relative custom field into the template is not such a complicated thing to do. You just test whether the particular field exists for the relevant post and, if the value is not empty, display it as such:

$meta_value = get_post_meta( $post->ID, 'customfield', true );
if (!empty( $meta_value )) {
echo $meta_value
}
else {
//do other stuff
};

The problem I happened across in this scenario is that I had multiple instances of a custom field being added to a post with different values, by virtue of Gravity Forms post submission, kind of like this:

The code above would retrieve the value of the custom field, but only one of them. I needed to be able to retrieve all values associated with the same metakey, by outputting them as an array. In a nutshell, that's what the below does. It grabs all values for a single custom field and outputs their values as a comma separated array.

$photos = get_post_meta( get_the_ID(), 'photos', false);
if( ! empty( $photos ) ) {
$photoURLs = array();
echo '<div class="photos-wrap">';
foreach ( $photos as $photo )
{
array_push($photoURLs,$photo);
}
$gallery = implode(", ",$photoURLs);
echo $gallery;
echo '</div>';
}

This works, but it literally only prints the values of the custom field - in this case, it outputs the URL stored as the value of the custom field "photos", as such:

http://localhost:8890/sandbox/wp-content/uploads/2020/11/image-1.jpeg, http://localhost:8890/sandbox/wp-content/uploads/2020/11/image-2.jpeg

Not quite what we are after, but we are much closer. As images, we would obviously want to display the images. What we now need to do is wrap each URL in an image tag. And we can achieve that with a little bit of jQuery. Key to making this work is wrapping the whole array in a containing div. That's what the photos-wrap div in the above code is for. The jQuery that does the legwork for us to wrap each URL within that container goes a little something like this:

$(document).ready(function() {
$(".photos-wrap").each(function(index) {
var links = $(this).html().split(', ');
$(this).empty().append(links.map(a => `<div class="thumb"><a href="${a}"><img src="${a}"></a></div>`)); 
});
});

I only used the anchor tag around each image to open the full picture in a FancyBox popup.

And there you have it - that's how you can display all image URLs stored as a custom field for a given post or custom post type.

Comments

Your email address will not be published. Required fields are marked *