在 WordPress 中通过文件路径获取附件 ID [英] Get attachment ID by file path in WordPress
本文介绍了在 WordPress 中通过文件路径获取附件 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道文件的路径,我喜欢获取附件 ID.
I know the path of the file and I like to get the attachment ID.
有一个函数 wp_get_attachment_url()
需要 ID获取 URL 但我需要它反向(虽然路径不是 URL)
There's a function wp_get_attachment_url()
which requires the ID to get the URL but I need it reverse (with path not URL though)
推荐答案
我使用了 pippinsplugins.com 截取的这个很酷的片段
I used this cool snipped by pippinsplugins.com
在你的functions.php文件中添加这个函数
Add this function in your functions.php file
// 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:
Then use this code in your page or template to store / print / use the 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-图片网址/
希望能帮到你;)弗朗切斯科
Hope ti helps ;) Francesco
这篇关于在 WordPress 中通过文件路径获取附件 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文