If you are referring to the 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 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 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 allshortcodes in the post content.
-
Use
get_post_gallery()
to retrieve the data of the firstshortcode in the post content.