WordPress开发函数attachment_url_to_postid(),尝试将附件URL转换为帖子ID。
用法:
attachment_url_to_postid( string $url )
参数:
$url
(string) (必需) 要解析的URL。
返回
(int)找到的post ID,失败时为0。
来源:
文件: wp-includes/media.php
function attachment_url_to_postid( $url ) {
global $wpdb;
$dir = wp_get_upload_dir();
$path = $url;
$site_url = parse_url( $dir[‘url’] );
$i**ge_path = parse_url( $path );
// Force the protocols to **tch if needed.
if ( isset( $i**ge_path[‘scheme’] ) &**p;&**p; ( $i**ge_path[‘scheme’] !== $site_url[‘scheme’] ) ) {
$path = str_replace( $i**ge_path[‘scheme’], $site_url[‘scheme’], $path );
}
if ( 0 === strpos( $path, $dir[‘baseurl’] . ‘/’ ) ) {
$path = substr( $path, strlen( $dir[‘baseurl’] . ‘/’ ) );
}
$sql = $wpdb->prepare(
“SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = ‘_wp_attached_file’ AND meta_value = s”,
$path
);
$results = $wpdb->get_results( $sql );
$post_id = null;
if ( $results ) {
// Use the first available result, but prefer a case-sensitive **tch, if exists.
$post_id = reset( $results )->post_id;
if ( count( $results ) > 1 ) {
foreach ( $results as $result ) {
if ( $path === $result->meta_value ) {
$post_id = $result->post_id;
break;
}
}
}
}
/**
* Filters an attachment ID found by URL.
*
* @since 4.2.0
*
* @par** int|null $post_id The post_id (if any) found by the function.
* @par** string $url The URL being looked up.
*/
return (int) apply_filters( ‘attachment_url_to_postid’, $post_id, $url );
}
更新日志:
用户贡献的笔记
(由Nil**bar Shar**于5年前贡献)
从附件URL获取帖子ID
echo attachment_url_to_postid( ‘http://ex**ple.com/wp-content/uploads/2016/05/castle-old.jpg’ );
输出:
123
暂无评论内容