is_local_attachment()WP 2.0.0

Determines whether the given URL is an attachment page of the current site.

Used to distinguish media files from your media library from external links before processing: generating thumbnails, substituting srcset, wrapping in markup, etc.

Notes

  • Returns true only for URLs of the current site; external domains always give false (including a CDN with a different domain).

  • The specified URL must be absolute with a protocol (http/https).

  • If the file is physically deleted, but the attachment post exists in the DB, the result will still be true.

  • In multisites the check applies to the current blog: a URL from another blog is considered external - will return false.

Use attachment_url_to_postid() to get the attachment ID.

1 time — 0.001947 sec (very slow) | 50000 times — 80.64 sec (very slow) | PHP 7.0.5, WP 4.4.2

No Hooks.

Returns

true|false.

Usage

if( is_local_attachment( $url ) ){
	// this is a file from the WordPress media library
}
$url(string) (required)
URL to check.

Examples

0

#1 Check the URL to see if this is an attachment

Let's say we have a link to a file in the wordpress media library: http://example.com/wp-content/uploads/2016/03/import.png and this file also has its own page in the frontend: http://example.com/attachment/import:

is_local_attachment( 'http://example.com/wp-content/uploads/2016/03/import.png' ); //> false

is_local_attachment( 'http://example.com/attachment/import' ); //> true

// nonexistent file
is_local_attachment( 'http://example.com/fooo' ); //> false

Changelog

Since 2.0.0 Introduced.

is_local_attachment() code WP 6.9.1

function is_local_attachment( $url ) {
	if ( ! str_contains( $url, home_url() ) ) {
		return false;
	}
	if ( str_contains( $url, home_url( '/?attachment_id=' ) ) ) {
		return true;
	}

	$id = url_to_postid( $url );
	if ( $id ) {
		$post = get_post( $id );
		if ( 'attachment' === $post->post_type ) {
			return true;
		}
	}
	return false;
}