attachment_url_to_postid()WP 4.0.0

Tries to convert an attachment URL into a post ID.

Hooks from the function

Return

Int. The found post ID, or 0 on failure.

Usage

attachment_url_to_postid( $url );
$url(string) (required)
The URL to resolve.

Examples

0

#1 Demo

The code below shows all the options and what the function will return. The last example shows how to get the ID of an attachment if a thumbnail link is passed: there the thumbnail size is cut out by regular expression.

$url = 'http://example.com/id_6643/proverka.html/prvoerka-vhodyashhih-dannyh';
$attachment_id = attachment_url_to_postid( $url ); // 0

$url = 'http://example.com/wp-content/uploads/2016/01/Prvoerka.jpg';
$attachment_id = attachment_url_to_postid( $url ); // 7704

$url = 'http://example.com/wp-content/uploads/2016/01/Prvoerka-80x80.jpg';
$attachment_id = attachment_url_to_postid( $url ); // 0

// remove the thumbnail size (-80x80) from the URL
$url = preg_replace( '~-[0-9]+x[0-9]+(?=\..{2,6})~', '', $url );
$attachment_id = attachment_url_to_postid( $url ); // 7704
0

#2 Custom function to get attachment ID via URL

/**
 * Gets attachment ID by URL.
 *
 * @param string $url File URI in any format. Even `image.jpg`.
 *
 * @return int Attachment id or 0.
 *
 * @version 1.2
 * @author Kama (wp-kama.ru)
 */
function kama_attachment_url_to_post_id( $url = '' ){
	global $wpdb;

	$url = filter_var( $url, FILTER_VALIDATE_URL );

	if ( $url === false ) {
		return 0;
	}

	$name = basename( $url ); // file name

	// remove the thumbnail size (-80x80)
	$name = preg_replace( '~-(?:\d+x\d+|scaled|rotated)~', '', $name );

	// delete extension
	$name = preg_replace( '~\.[^.]+$~', '', $name );

	// $name = sanitize_file_name( $name );

	$post_name = sanitize_title( $name );

	// filter by index field post_name
	$sql = $wpdb->prepare(
		"SELECT ID, guid FROM $wpdb->posts WHERE post_name LIKE %s AND post_title = %s AND post_type = 'attachment'",
		$wpdb->esc_like( $post_name ) .'%', $name
	);

	$attaches = $wpdb->get_results( $sql );

	if( ! $attaches ){
		return 0;
	}

	$attachment_id = reset( $attaches )->ID;

	// several are found, let's decide which one to take
	if( count( $attaches ) > 1 ){

		$url_path = parse_url( $url, PHP_URL_PATH );

		foreach( $attaches as $attach ){

			if( false !== strpos( $attach->guid, $url_path ) ){
				$attachment_id = $attach->ID;
				break;
			}
		}
	}

	return (int) apply_filters( 'kama_attachment_url_to_post_id', $attachment_id, $url );
}
// Examples of function calls
$id = attachment_url_to_post_id( 'http://test-wp.ru/wp-content/uploads/2017/02/Lighthouse.jpg' );
$id = attachment_url_to_post_id( 'wp-content/uploads/2017/02/Lighthouse.jpg' );
$id = attachment_url_to_post_id( 'oads/2017/02/Lighthouse.jpg' );

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 4.0.0 Introduced.

attachment_url_to_postid() code WP 6.4.3

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 );
}