Only current gallery images with get_attached_media

On my page the gallery images are cycled and I would like to show their title as a caption. Since get_post_gallery_images only retrieves the thumbnail-url of the gallery images I have tried to use get_attached_media('image', $post); instead.

The following code gives me the url and the title of the gallery images:

foreach($images as $image) { $titleArr[] = $image->post_title; $urlArr[] = wp_get_attachment_url($image->ID); }

However, get_attached_media('image', $post); returns all images that have ever been attached to this post, even if they are no longer used in the post. Also, for posts where the gallery images are attached to another post, they do not appear.

Is there an equivalent of get_attached_media('image', $post); that returns all the image urls and titles of the images currently in the gallery. Preferably in gallery order.

Topic media gallery images Wordpress

Category Web


Found an answer using Shortcode which helped: How to get Page/Post Gallery attachment images in order they are set in backend using WP_Query()?

My working code now looks like this:

// Extract the shortcode arguments from the $page or $post
$shortcode_args = shortcode_parse_atts(get_match('/\[gallery\s(.*)\]/isU', $post->post_content));

// get the ids specified in the shortcode call
$ids = $shortcode_args["ids"];

$attachments = get_posts(
    array(
        'include' => $ids, 
        'post_status' => 'inherit', 
        'post_type' => 'attachment', 
        'post_mime_type' => 'image', 
        'order' => 'menu_order ID', 
        'orderby' => 'post__in', //required to order results based on order specified the "include" param
    )
);

if ($attachments) {
        foreach ( $attachments as $attachment ) {
    $urlArr[] = wp_get_attachment_url($attachment->ID);
    $titleArr[] = $attachment->post_title;
        }
    }

About

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