WordPress开发函数attachment_url_to_postid()
WordPress开发函数attachment_url_to_postid(),尝试将附件URL转换为帖子ID…
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’] );
$image_path = parse_url( $path );
// Force the protocols to match if needed.
if ( isset( $image_path[‘scheme’] ) && ( $image_path[‘scheme’] !== $site_url[‘scheme’] ) ) {
$path = str_replace( $image_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 match, 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
*
* @param int|null $post_id The post_id (if any) found by the function.
* @param string $url The URL being looked up.
*/
return (int) apply_filters( ‘attachment_url_to_postid’, $post_id, $url );
}
更新日志:
用户贡献的笔记
(由Nilambar Sharma于5年前贡献)
从附件URL获取帖子ID
echo attachment_url_to_postid( ‘http://example.com/wp-content/uploads/2016/05/castle-old.jpg’ );
输出:
123
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!