is_local_attachment()
云策文档标注
概述
is_local_attachment() 函数用于检查一个 URL 是否为本地附件。它通过验证 URL 是否属于当前站点,并确认其对应的文章类型为 'attachment' 来实现。
关键要点
- 函数接受一个 URL 参数,返回布尔值:true 表示是本地附件,false 表示不是。
- 检查逻辑包括:URL 是否包含 home_url(),是否为特定附件 ID 格式,或通过 url_to_postid() 和 get_post() 验证文章类型。
- 该函数在 WordPress 2.0.0 版本引入,常用于 pingback() 等场景。
代码示例
// 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 a local attachment.', 'your-text-domain' ),
esc_url( $url )
);
}
原文内容
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
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
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
Himani Panchal
// 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 ) ); }