is_local_attachment( string $url ): bool

Determines whether an attachment URI is local and really an attachment.

Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Parameters

$urlstringrequired
URL to check

Return

bool True on success, false on failure.

Source

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

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 2 content
    // Example
    $url = 'https://example.com/uploads/yourimage.jpg';
    
    if ( is_local_attachment( $url ) ) {
        printf(
            esc_html__( '%s is a local attachment.', 'your-text-domain' ),
            esc_url( $url )
        );
    } else {	
        printf(
            esc_html__( '%s is not alocal attachment.', 'your-text-domain' ),
            esc_url( $url )
        );
    }

You must log in before being able to contribute a note or feedback.