WordPress通过图片URL地址获取 ID

WordPress图片编有ID号,存放在postmeta表中。通过图片URL地址获取ID的需求在对图片进行重定义等操作中会使用到。
function monseng_get_attachment_id ($img_url) {
$cache_key = md5($img_url);
$post_id = wp_cache_get($cache_key, 'monseng_attachment_id' );
if($post_id == false){
$attr = wp_upload_dir();
$base_url = $attr['baseurl']."/";
$path = str_replace($base_url, "", $img_url);
if($path){
global $wpdb;
$post_id = $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE meta_value = '{$path}'");
$post_id = $post_id?$post_id:'';
}else{
$post_id = '';
}
wp_cache_set( $cache_key, $post_id, 'monseng_attachment_id', 86400);
}
return $post_id;
}
调用方法:


#现在前往

精选留言

WordPress,通过,图片,URL
sample
2021-05-30
写留言
签到
投稿
QQ咨询
返回顶部