Search code examples
wordpresspreg-matchgalleryimage-galleryshortcode

Display all post image gallery using the shortcode [gallery]


I want to display the images from the post gallery with the "gallery". Like that :<?php echo do_shortcode('[gallery]'); ?>

After some search, I learned that we needed to use a "preg_match" function to get the ids of the images gallery. Something like that :

$post_content = $post->post_content;
preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
$array_id = explode(",", $ids[1]);

But I don't know how to use it ... I'm a newbie and it's quite difficult for me to use that. Should I put this code in my functions file ? If yes how can I do that please ?

The aim it's to put a final code like that : <?php echo do_shortcode( '[gallery ids="$array_id"]' ); ?>

Thank you and sorry for my english !!!


Solution

  • I found the solution, so I share this with you. Maybe someone will be interested by that.

    I modified the following code :

    $post_content = $post->post_content;
    preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
    $array_id = explode(",", $ids[1]);
    

    Into :

    <?php
    global $post;
    
        $post_content = $post->post_content;
        preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
        $images_id = explode(",", $ids[1]);
    echo do_shortcode('[gallery type="slideshow" ids="'. implode(',', array_slice($images_id, 0, 3)).' ,"]');
    ?>
    

    And I inserted this in my custom format-gallery.php and it works so fine. Notice that I have limited automatically the number of ids returned with an array_slice().

    I hope that will help someone.