List all images from a single post meta value

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).'"';
 }
}
?

Topic post-meta images custom-field custom-post-types Wordpress

Category Web


Get images from Gallery Custom Post Meta

  <?php 
    $meta = get_post_meta(get_the_ID(), 'gallery');
    foreach ($meta as $m) :
    $img_atts = wp_get_attachment_image_src( $m, $default );
    $img_src = $img_atts[0];
  ?>
        <div class="swiper-slide"><img src="<?php echo $img_src ?>" alt=""></div>

  <?php endforeach ?>

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?

Yes. get_post_meta(...) should return an array without that last parameter, or with it set to false. You'd then have...

<?php
$meta = get_post_meta($post->ID, 'gallery-upload');
foreach ($meta as $m) {
    echo '<img src="'.$m.'">'; 
} 
?>

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:

$args = array( 
   'post_mime_type' => 'image',
   'numberposts'    => -1,
   'post_parent'    => get_the_ID(),
   'post_type'      => 'attachment' 
);

$attached_images = get_children( $args );

foreach ( $attached_images as $image )
{
    // print image
}

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).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.