is_local_attachment()
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
trueonly 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.
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
#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() 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;
}