I have created a custom post type with an image gallery upload. Now I am trying to display the gallery on the front end. This is what I have so far that works to display 1 image, but if multiple images are uploaded all the URLs get stuck in the src
tag. So I’m guessing I should loop through that array and spit out each one separately? Would that be the route to go and if so how can I accomplish this?
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
echo '<img src="'.get_post_meta($post->ID, 'gallery-upload', true).'">';
?>
<?php endwhile; else: ?>
<p><?php _e('No posts were found. Sorry!'); ?></p>
<?php endif; ?>
EDIT:
This is what I ended up with that works…
<?php
foreach(get_post_meta($post->ID, 'gallery-upload') as $meta) {
foreach(explode(',', $meta) as $src) {
echo '<img src="'.htmlentities($src).'">';
}
}
?>
You should reorganize the way you store the images: Make the uploaded files children of that particular post, do not put them in a post meta field. Then get all the images with
get_children()
. Look at the built-in handler for the[gallery]
shortcode for some examples.I should go like this:
And even if you want to stay with post meta fields, do not store URLs, use the attachment IDs instead. URLs can change any time (think about a migration from dev to production site).
Yes.
get_post_meta(...)
should return an array without that last parameter, or with it set to false. You’d then have…Get images from Gallery Custom Post Meta