Forum

How to Get All Imag...
 
Notifications
Clear all

How to Get All Images in A WordPress Page from Media Gallery?

 
Barnali
(@barnali)
Active Member

What is the process for retrieving all images from a WordPress page's media gallery? Is it possible to programmatically query the media gallery to get a list of images and their associated metadata, such as image titles and captions? Are there any best practices or considerations to keep in mind when working with WordPress media galleries and images in this way?

Quote
Topic starter Posted : 08/04/2023 11:59 am
(@administrator)
Member Admin

Ok, There was WordPress Plugin but that plugin is outdated right now. Let me tell you an easy way.

Install PHP code plugins like insert php code snippet or similar plugins.

 

Then use this php code.

 

<?php
$query_images_args = array(
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'post_status'    => 'inherit',
    'posts_per_page' => -1,
);

$query_images = new WP_Query($query_images_args);

$gallery_items = '';
if ($query_images->have_posts()) {
    while ($query_images->have_posts()) {
        $query_images->the_post();
        $post_id = get_post_field('post_parent', get_the_ID());
        $post_status = get_post_status($post_id);
        if ($post_id && $post_status === 'publish') {
            $post_permalink = get_permalink($post_id);
            $image_url = wp_get_attachment_image_src(get_the_ID(), 'thumbnail')[0];
            $gallery_items .= '<a href="' . $post_permalink . '"><img src="' . $image_url . '"></a>';
        }
    }
}

echo '<div class="gallery gallery-columns-3 gallery-size-thumbnail" style="display: flex; flex-wrap: wrap; gap: 5px;">' . $gallery_items . '</div>';
wp_reset_postdata();
?>

 

Save the code, it will generate a short code to copy-paste where you want to show. It will show all images that post are published on your WordPress blog. If want to see a live example go here.

Hope it will help you.

Thanks.

This post was modified 1 year ago by Administrator
ReplyQuote
Posted : 08/04/2023 12:11 pm
Barnali reacted
Barnali
(@barnali)
Active Member

Thank you so much sir, You are my game changer. I installed the plugin and setup the code, it is fully working. 👍 👍 👍 ❤️ ❤️ ❤️ 

ReplyQuote
Topic starter Posted : 08/04/2023 12:23 pm
Share:
×