1

I can get post attachment images it is ok. But i want to get attachments from only post's gallery? Is it possible?

Here is my code:

global $post;
$id = $post->ID;
$post = get_post($post);
$images =& get_children( 'post_type=attachment&post_mime_type=image&output=ARRAY_N&orderby=menu_order&order=DESC&post_parent='.$post->post_parent);
  • Posts can have multiple galleries, and each can be customized to display different images. They're added directly to the post HTML content via a [gallery] shortcode and aren't recorded anywhere else. So, there's no programmatic way to get attachments from a gallery in a post. – SeventhSteel Jul 18 '18 at 16:00
  • You could search the content for a gallery shortcode, parse the IDs then request each image separately. I'm sure you don't want to do that, but you could. – jdm2112 Jul 18 '18 at 16:54
  • Is there only one gallery per post or more of them? – Krzysiek Dróżdż Jul 18 '18 at 19:51
1

If you are referring to the [gallery] shortcode, then you can use the get_post_gallery() or get_post_galleries() function to retrieve the gallery data such as ids (a list of IDs separated with comma) and src (an array of image URLs).

Sample code #1: (using get_post_gallery())

1234 is the ID of the post containing the [gallery] shortcode.

$galry = get_post_gallery( 1234, false );
$images = [];
if ( $galry && isset( $galry['ids'] ) ) {
    $ids = wp_parse_id_list( $galry['ids'] );
    $images = get_posts( [
        'post__in'  => $ids,
        'post_type' => 'attachment',
    ] );
    echo 'Number of images in gallery #1:<br>';
    echo count( $images ) . '<br>';
}

Sample code #2: (using get_post_galleries())

1234 is the ID of the post containing the [gallery] shortcodes.

$galrys = get_post_galleries( 1234, false );
foreach ( $galrys as $i => $galry ) {
    $ids = wp_parse_id_list( $galry['ids'] );
    $images = get_posts( [
        'post__in'  => $ids,
        'post_type' => 'attachment',
    ] );
    echo 'Number of images in gallery #' . ( $i + 1 ) . ':<br>';
    echo count( $images ) . '<br>';
}

So:

  • Use get_post_galleries() to retrieve the data of all [gallery] shortcodes in the post content.

  • Use get_post_gallery() to retrieve the data of the first [gallery] shortcode in the post content.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.