get gallery images from advanced custom field Editor

1.2k Views Asked by At

I have created a meta box with editor using advanced custom field plugin

This meta box displays a text editor from which i am able to create and add Gallery to the post.

But while retrieving the gallery data.

$gallery = get_post_meta($post->ID, 'gallery', true);     
echo $gallery;

this displays

[gallery ids="53,54,55,56"]

Generally, the gallery data can be retrived like

$galleries = get_post_gallery_images( get_the_ID() ); 

But this does not seem to work if I am using a meta box to save the gallery.

Is there a wordpress way to get the gallery images and loop through them and display those image in lightbox or should i try any other method?

3

There are 3 best solutions below

0
On BEST ANSWER

This did the trick

<?php
$gallery = get_post_meta($post->ID, 'gallery', true);

preg_match('/\[gallery.*ids=.(.*).\]/', $gallery, $ids);
$images_id = explode(",", $ids[1]);
if ($images_id[0] != "") {
    if (is_array($images_id) || is_object($images_id)) {
        foreach ($images_id as $image) {
            $image_url = wp_get_attachment_image_src($image, 'banner');
            ?>
            <a href="<?php echo $image_url[0]; ?>">
                <?php echo wp_get_attachment_image($image, 'destinatoin', 'false', array("class" => "img-responsive")); ?>
            </a>
        <?php }
    }
} ?>

What should be done is

preg_match('/\[gallery.*ids=.(.*).\]/', $gallery, $ids);
$images_id = explode(",", $ids[1]);

which will create a array of ids then I can loop through the images by

   foreach ($images_id as $image) {
        $image_url = wp_get_attachment_image_src($image, 'banner');
        ?>
        <a href="<?php echo $image_url[0]; ?>">
            <?php echo wp_get_attachment_image($image, 'destinatoin', 'false', array("class" => "img-responsive")); ?>
        </a>
    <?php }
0
On

Not possible because I think you are not inserting the gallery short code into posts editor, so $galleries = get_post_gallery_images( get_the_ID() ); come with nothing.

So into your meta box filed put just image ids, like

"53,54,55,56"

and

$gallery = get_post_meta($post->ID, 'gallery', true);

$gallery variable will return a coma separated string, then explode it by $gallery_image_array = explode($gallery);

Then $gallery_image_array will have a image ids, So you can loop through it, and you can get those images by wp_get_attachment_image_src

and print it as you want :)

3
On

1st I am assuming that You had put "[gallery ids="53,54,55,56"]" this short code under the meta filed that why

$gallery = get_post_meta($post->ID, 'gallery', true);
echo $gallery;

Return

[gallery ids="53,54,55,56"]

can try this

$gallery = get_post_meta($post->ID, 'gallery', true);
echo do_shortcode($gallery);

And

$galleries = get_post_gallery_images( get_the_ID() );

Returns a list of array of image items with image upload sources.