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

function attachment_url_to_postid( $url ) {
	global $wpdb;

	$dir  = wp_get_upload_dir();
	$path = $url;

	$site_url   = parse_url( $dir['url'] );
	$image_path = parse_url( $path );

	// Force the protocols to match if needed.
	if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
		$path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
	}

	if ( str_starts_with( $path, $dir['baseurl'] . '/' ) ) {
		$path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
	}

	$sql = $wpdb->prepare(
		"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
		$path
	);

	$results = $wpdb->get_results( $sql );
	$post_id = null;

	if ( $results ) {
		// Use the first available result, but prefer a case-sensitive match, if exists.
		$post_id = reset( $results )->post_id;

		if ( count( $results ) > 1 ) {
			foreach ( $results as $result ) {
				if ( $path === $result->meta_value ) {
					$post_id = $result->post_id;
					break;
				}
			}
		}
	}

	/**
	 * Filters an attachment ID found by URL.
	 *
	 * @since 4.2.0
	 *
	 * @param int|null $post_id The post_id (if any) found by the function.
	 * @param string   $url     The URL being looked up.
	 */
	return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
}

Hooks

apply_filters( ‘attachment_url_to_postid’, int|null $post_id, string $url )

Filters an attachment ID found by URL.

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.