In WordPress, you can get the ID of the first image in an image gallery from a block on another page using the following code:
phpCopy code$first_image_id = 0;
$post = get_post( $post_id );
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( 'gallery', $matches[2] ) )
{
$keys = array_keys( $matches[2], 'gallery' );
foreach ( $keys as $key ) {
$attrs = shortcode_parse_atts( $matches[3][$key] );
if ( array_key_exists( 'ids', $attrs ) ) {
$image_ids = explode( ',', $attrs['ids'] );
$first_image_id = $image_ids[0];
break;
}
}
}
This code retrieves the post content for the specified $post_id
, then uses a regular expression to search for any shortcodes. If any are found, it loops through the shortcodes and retrieves the
ids
attribute, which is a comma-separated list of image IDs. The first image ID is stored in the $first_image_id
variable.
(Visited 1 times, 1 visits today)
Was this article helpful?
YesNo
Last modified: March 3, 2023