我在我的一些项目中也有类似的需求,通过从其URL获取图像ID,然后使用wp_get_attachment_image
因为它将返回带有srcset属性的标记。
为了获取图像ID,我使用Gustavo Bordoni的助手,如下所示here.
function attachment_url_to_postid( $url ) {
global $wpdb;
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir[\'baseurl\'] . \'/\' ) ) {
$path = substr( $path, strlen( $dir[\'baseurl\'] . \'/\' ) );
}
$sql = $wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = \'_wp_attached_file\' AND meta_value = %s",
$path
);
$post_id = $wpdb->get_var( $sql );
if ( ! empty( $post_id ) ) {
return (int) $post_id;
}
}
函数attachment\\u url\\u to\\u posted($url){全局$wpdb;
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir[\'baseurl\'] . \'/\' ) ) {
$path = substr( $path, strlen( $dir[\'baseurl\'] . \'/\' ) );
}
$sql = $wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = \'_wp_attached_file\' AND meta_value = %s",
$path
);
$post_id = $wpdb->get_var( $sql );
if ( ! empty( $post_id ) ) {
return (int) $post_id;
}
}
这是包装纸:
function get_attachment_id_by_url( $url ) {
$post_id = attachment_url_to_postid( $url );
if ( ! $post_id ){
$dir = wp_upload_dir();
$path = $url;
if ( 0 === strpos( $path, $dir[\'baseurl\'] . \'/\' ) ) {
$path = substr( $path, strlen( $dir[\'baseurl\'] . \'/\' ) );
}
if ( preg_match( \'/^(.*)(\\-\\d*x\\d*)(\\.\\w{1,})/i\', $path, $matches ) ){
$url = $dir[\'baseurl\'] . \'/\' . $matches[1] . $matches[3];
$post_id = attachment_url_to_postid( $url );
}
}
return (int) $post_id;
}
然后,标记:
wp_get_attachment_image( $image_id, $args[\'desired_image_size_as_registered\'] );
希望有帮助。