在 WordPress 中通过文件路径获取附件 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25671108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get attachment ID by file path in WordPress
提问by Xaver
I know the path of the file and I like to get the attachment ID.
我知道文件的路径,我喜欢获取附件 ID。
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)
有一个函数wp_get_attachment_url()需要 ID 来获取 URL,但我需要它反向(虽然路径不是 URL)
回答by Luca Reghellin
UPDATE: since wp 4.0.0 there's a new function that could do the job. I didn't tested it yet, but it's this:
更新:从 wp 4.0.0 开始,有一个新功能可以完成这项工作。我还没有测试它,但它是这样的:
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
OLD ANSWER: so far, the best solution I've found out there, is the following:
旧答案:到目前为止,我发现的最佳解决方案如下:
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
I think It's the best for 2 reasons:
我认为这是最好的有两个原因:
- It does some integrity checks
- [important!] it's domain-agnostic. This makes for safe site moving. To me, this is a key feature.
- 它会做一些完整性检查
- [重要!] 它与域无关。这有助于安全的站点移动。对我来说,这是一个关键功能。
回答by FrancescoCarlucci
I used this cool snipped by pippinsplugins.com
我使用了 pippinsplugins.com 截取的这个很酷的片段
Add this function in your functions.php file
在你的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];
}
Then use this code in your page or template to store / print / use the ID:
然后在您的页面或模板中使用此代码来存储/打印/使用 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;
Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
原帖在这里:https: //pippinsplugins.com/retrieve-attachment-id-from-image-url/
Hope ti helps ;) Francesco
希望 ti 有帮助 ;) Francesco
回答by Rubel Miah
Try attachment_url_to_postidfunction.
试试attachment_url_to_postid功能。
$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;
回答by random_user_name
None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin's function also is flawed, and doesn't really do things "the WordPress Way".
对于文件路径,这里的其他任何答案似乎都不能正常或可靠地工作。使用 Pippin 函数的答案也有缺陷,并没有真正按照“WordPress 方式”做事。
This function will support either a path OR a url, and relies on the built-in WordPress function attachment_url_to_postid to do the final processing properly:
此函数将支持路径或 url,并依赖于 WordPress 内置函数attachment_url_to_postid 正确进行最终处理:
/**
* Find the post ID for a file PATH or URL
*
* @param string $path
*
* @return int
*/
function find_post_id_from_path( $path ) {
// detect if is a media resize, and strip resize portion of file name
if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
$path = str_ireplace( $matches[1], '', $path );
}
// process and include the year / month folders so WP function below finds properly
if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
unset( $matches[0] );
$path = implode( '', $matches );
}
// at this point, $path contains the year/month/file name (without resize info)
// call WP native function to find post ID properly
return attachment_url_to_postid( $path );
}
回答by GFargo
Cropped URLs
裁剪的 URL
None of the previous answers supported ID lookup on attachment URLs that contain a crop.
以前的答案都不支持对包含裁剪的附件 URL 进行 ID 查找。
e.g: /uploads/2018/02/my-image-300x250.jpgv.s. /uploads/2018/02/my-image.jpg
例如:/uploads/2018/02/my-image-300x250.jpgvs/uploads/2018/02/my-image.jpg
Solution
解决方案
Micah at WP Scholar wrote a blog postand uploaded the code to this Gist. It handles both original and cropped URL lookup.
WP Scholar 的 Micah 写了一篇博文并将代码上传到这个Gist。它处理原始和裁剪的 URL 查找。
I included the code below as a reference but, if you find useful, I'd encourage you to leave a comment on his post or starthe gist.
我在下面包含了代码作为参考,但是,如果您觉得有用,我鼓励您在他的帖子上发表评论或为要点加注星标。
/**
* Get an attachment ID given a URL.
*
* @param string $url
*
* @return int Attachment ID on success, 0 on failure
*/
function get_attachment_id( $url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory?
$file = basename( $url );
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta['file'] );
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' );
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
Another pro with this solution is that we leverage the WP_Queryclass instead of making a direct SQL query to DB.
此解决方案的另一个优点是我们利用WP_Query该类而不是对 DB 进行直接 SQL 查询。
回答by Julian F. Weinert
Based on the answer from @FrancescoCarlucci I could do some improvements.
根据@FrancescoCarlucci 的回答,我可以做一些改进。
Sometimes, for example when you edit an image in WordPress, it creates a copy from the original and adds the copys upload path as post meta (key _wp_attached_file) which is not respected by the answer.
有时,例如,当您在 WordPress 中编辑图像时,它会从原始图像创建一个副本,并将副本上传路径添加为 post meta (key _wp_attached_file),这不受答案的尊重。
Here the refined query that includes these edits:
这是包含这些编辑的优化查询:
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];
}

