The is_local_attachment() WordPress PHP function determines whether an attachment URI is local and really an attachment.
Usage
$is_local = is_local_attachment( $url );
Example:
$url = 'https://example.com/wp-content/uploads/2023/05/image.jpg';
$is_local = is_local_attachment( $url );
if ( $is_local ) {
echo 'This is a local attachment.';
} else {
echo 'This is not a local attachment.';
}
Parameters
$url(string) – Required. URL to check.
More information
See WordPress Developer Resources: is_local_attachment
Examples
Check if an image is a local attachment
This example checks if an image URL is a local attachment and displays a message accordingly.
$image_url = 'https://example.com/wp-content/uploads/2023/05/my-image.jpg';
if ( is_local_attachment( $image_url ) ) {
echo 'The image is a local attachment.';
} else {
echo 'The image is not a local attachment.';
}
Display attachment metadata if local
This example checks if a given URL is a local attachment, and if so, displays its metadata.
$attachment_url = 'https://example.com/wp-content/uploads/2023/05/document.pdf';
if ( is_local_attachment( $attachment_url ) ) {
$attachment_id = attachment_url_to_postid( $attachment_url );
$attachment_metadata = wp_get_attachment_metadata( $attachment_id );
print_r( $attachment_metadata );
} else {
echo 'The document is not a local attachment.';
}
Add a CSS class to local attachments
This example adds a CSS class to local attachment image URLs within an array of URLs.
$image_urls = array(
'https://example.com/wp-content/uploads/2023/05/image1.jpg',
'https://example.com/wp-content/uploads/2023/05/image2.jpg',
'https://external.com/images/image3.jpg'
);
foreach ( $image_urls as $image_url ) {
if ( is_local_attachment( $image_url ) ) {
echo "<img src='{$image_url}' class='local-attachment' />";
} else {
echo "<img src='{$image_url}' />";
}
}
Filter an array of URLs for local attachments
This example filters an array of URLs and returns only the local attachment URLs.
$urls = array(
'https://example.com/wp-content/uploads/2023/05/image1.jpg',
'https://example.com/wp-content/uploads/2023/05/document.pdf',
'https://external.com/images/image2.jpg'
);
$local_attachments = array_filter( $urls, 'is_local_attachment' );
print_r( $local_attachments );
Count local attachments in an array of URLs
This example counts the number of local attachment URLs in an array of URLs.
$urls = array(
'https://example.com/wp-content/uploads/2023/05/image1.jpg',
'https://example.com/wp-content/uploads/2023/05/document.pdf',
'https://external.com/images/image2.jpg'
);
$local_attachment_count = count( array_filter( $urls, 'is_local_attachment' ) );
echo "Number of local attachments: {$local_attachment_count}";