attachment_url_to_postid( string $url ): int

Tries to convert an attachment URL into a post ID.

Parameters

$urlstringrequired
The URL to resolve.

Return

int The found post ID, or 0 on failure.

Source

if ( $has_inner_blocks && $html ) {
	$block_html  = wp_list_pluck( $block['innerBlocks'], 'innerHTML' );
	$galleries[] = '<figure>' . implode( ' ', $block_html ) . '</figure>';
	continue;
}

$srcs = array();

// New Gallery block format as an array.
if ( $has_inner_blocks ) {
	$attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' );
	$ids   = wp_list_pluck( $attrs, 'id' );

	foreach ( $ids as $id ) {
		$url = wp_get_attachment_url( $id );

		if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
			$srcs[] = $url;
		}
	}

	$galleries[] = array(
		'ids' => implode( ',', $ids ),
		'src' => $srcs,
	);

	continue;
}

// Old Gallery block format as HTML.
if ( $html ) {
	$galleries[] = $block['innerHTML'];
	continue;
}

// Old Gallery block format as an array.
$ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array();

// If present, use the image IDs from the JSON blob as canonical.
if ( ! empty( $ids ) ) {
	foreach ( $ids as $id ) {
		$url = wp_get_attachment_url( $id );

		if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
			$srcs[] = $url;
		}
	}

	$galleries[] = array(
		'ids' => implode( ',', $ids ),

Changelog

VersionDescription
4.0.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Applying WordPress coding standards and best practices, example should look like this, Muhibul.

    $attachment_url     = 'https://example.com/wp-content/uploads/2023/09/image.jpg';
    $attachment_post_id = attachment_url_to_postid( esc_url( $attachment_url ) );
    
    if ( 0 !== $attachment_post_id ) {
        // An attachment post or page was found.
        printf( esc_html__( 'Attachment is associated with post ID: %s', 'textdomain'),
            $attachment_post_id
        );
    } else {
        // No attachment post or page found for the URL.
        esc_html_e( 'No post or page found for the provided attachment URL.', 'textdomain');
    }

You must log in before being able to contribute a note or feedback.