2014-09-04 99 views

回答

7

我用这个凉爽剪断通过pippinsplugins.com

在添加此功能时,您functions.php文件

// retrieves the attachment ID from the file URL 
function pippin_get_image_id($image_url) { 
    global $wpdb; 
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url)); 
     return $attachment[0]; 
} 

然后在你的页面或模板使用此代码来存储/打印/使用ID:

// set the image url 
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg'; 

// store the image ID in a var 
$image_id = pippin_get_image_id($image_url); 

// print the id 
echo $image_id; 

原帖在这里:https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

希望TI帮助;) 弗朗切斯科

+0

这是路径而不是网址我有,但您的解决方案工作(有小调整)谢谢! – Xaver 2014-09-04 19:00:19

+0

很高兴听到这个;) – FrancescoCarlucci 2014-09-04 19:24:15

12

UPDATE:因为WP 4.0.0有一个新的功能,可以做的工作。我没有测试它,但它是这样的:

https://developer.wordpress.org/reference/functions/attachment_url_to_postid/


迟到的回答:到目前为止,我已经找到了最好的解决方案有这样一句:

http://frankiejarrett.com/get-an-attachment-id-by-url-in-wordpress/

我认为这是最好的有两个原因:

  • 它确实有些完整性CHEC ks
  • [important!]它是域不可知的。这使得安全的网站移动。对我而言,这是一个关键功能。
+0

这应该是被接受的答案。 WordPress函数中使用的方法比依赖guid更强大。阅读Pippins页面的评论以了解限制。 – Mark 2017-05-24 07:44:07

-1

根据@FrancescoCarlucci的回答,我可以做一些改进。

有时,例如当您在WordPress中编辑图像时,它会从原始文件创建一个副本,并将副本上传路径添加为后期元(键为_wp_attached_file),这不受答案的限制。

这里经过优化的查询,包括这些编辑:

function jfw_get_image_id($file_url) { 
    $file_path = ltrim(str_replace(wp_upload_dir()['baseurl'], '', $file_url), '/'); 

    global $wpdb; 
    $statement = $wpdb->prepare("SELECT `ID` FROM `wp_posts` AS posts JOIN `wp_postmeta` AS meta on meta.`post_id`=posts.`ID` WHERE posts.`guid`='%s' OR (meta.`meta_key`='_wp_attached_file' AND meta.`meta_value` LIKE '%%%s');", 
     $file_url, 
     $file_path); 

    $attachment = $wpdb->get_col($statement); 

    if (count($attachment) < 1) { 
     return false; 
    } 

    return $attachment[0]; 
}