如何从WordPress附件页面URL中获取对应的附件ID
WordPress获取附件ID的通用解决方案
针对附件页面URL的获取方法
attachment_url_to_postid原生仅支持解析媒体文件直链,无法适配附件页URL,可通过提取URL中的附件slug查询ID:
// 传入你的附件页面URL $attachment_page_url = 'http://localhost/site/custom-post/post-name/screenshot_20211005-091742/'; // 提取URL路径中的最后一段作为附件slug $url_path = parse_url($attachment_page_url, PHP_URL_PATH); $path_segments = array_filter(explode('/', $url_path)); $attachment_slug = end($path_segments); // 查询附件数据,post_type固定为attachment $attachment_post = get_page_by_path($attachment_slug, OBJECT, 'attachment'); $attachment_id = $attachment_post ? $attachment_post->ID : 0;
针对媒体直链调用attachment_url_to_postid返回0的解决方案
返回0的常见原因
- 站点上传目录非默认
wp-content/uploads,内置函数路径匹配失效 - URL的域名、协议(http/https)、前缀与后台设置的
siteurl/home不匹配 - 文件名大小写与数据库中存储的不一致,Linux环境下会匹配失败
自定义查询实现
跳过路径匹配逻辑,直接通过文件名模糊查询附件ID:
/** * 从媒体文件URL获取附件ID,兼容自定义上传目录、域名不一致场景 * @param string $file_url 媒体文件直链 * @return int 附件ID,查询失败返回0 */ function custom_get_attachment_id_by_url( $file_url ) { global $wpdb; // 提取文件名 $file_name = basename( $file_url ); // 模糊匹配guid字段中的文件名 $query_result = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND guid LIKE %s", '%' . $wpdb->esc_like( $file_name ) . '%' ) ); return empty($query_result) ? 0 : (int)$query_result[0]; } // 调用示例 $attachment_id = custom_get_attachment_id_by_url('http://localhost/site/wp-content/uploads/2021/10/S036662860_0.jpg');
注意事项
如果站点存在大量同名媒体文件,可额外增加post_date等条件过滤,避免返回错误ID。
内容的提问来源于stack exchange,提问作者Sheldon
相关产品推荐
相关产品推荐

