2011-03-30 73 views
0

我正在使用自定义字段来选择图片的网址。基于网址的wordpress图片大小

我的客户端正在插入并上传所有图片,因此这需要非常简单。这就是为什么我试图在幕后处理它。

我遇到的问题是我在全尺寸图像的网址中确实减慢了加载时间。

有没有办法根据完整大小的网址插入缩略图或其他图片大小?

我试过这种工作方式,但我遇到的问题是一些图像没有相同的牙列,所以这需要做更多的动态。

<? $reduceimage = str_replace('.jpg', '-330x220.jpg' , $defaultimage); ?> 
+0

如何动态这是否必要呢?你有一个特定的宽度,你需要修剪图像? '-330x220.jpg'是否会使用一些WP魔术自动将图像变成缩略图?你可以使用/你知道图像的文件系统路径吗? – 2011-03-30 15:42:30

+0

我有绝对的网址,以全尺寸的图像。我的问题是我正在寻找显示最大宽度为330和最大高度为220的中等大小的图像。问题是这些图像中的某些在上传/调整大小时未达到最大宽度或高度,由wordpress根据图像方面的无线电。例如,很多图像是330x220,但其他图像的中等大小 - 330×247。 – Adam 2011-03-30 15:54:16

+0

在这些情况下您想要发生什么?没有调整大小? – 2011-03-30 16:03:21

回答

0

我认为这是最好的依靠WordPress的本地wp_get_attachment_image_src()函数来获取图像的大小不同。但要这样做,你需要附件ID,而不是网址。 功能的URL转换为ID:

function fjarrett_get_attachment_id_by_url($url) { 

    // Split the $url into two parts with the wp-content directory as the separator 
    $parsed_url = explode(parse_url(WP_CONTENT_URL, PHP_URL_PATH), $url); 

    // Get the host of the current site and the host of the $url, ignoring www 
    $this_host = str_ireplace('www.', '', parse_url(home_url(), PHP_URL_HOST)); 
    $file_host = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST)); 

    // Return nothing if there aren't any $url parts or if the current host and $url host do not match 
    if (! isset($parsed_url[1]) || empty($parsed_url[1]) || ($this_host != $file_host)) { 
     return; 
    } 

    // Now we're going to quickly search the DB for any attachment GUID with a partial path match 

    // Example: /uploads/2013/05/test-image.jpg 
    global $wpdb; 
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1])); 

    // Returns null if no attachment is found 
    return $attachment[0]; 
} 

感谢Frankie Jarrett

然后你就可以轻松地获得其他尺寸:

$medium_image = wp_get_attachment_image_src(fjarrett_get_attachment_id_by_url($image_link), 'medium'); 

如果从这一形象需要链接:

$medium_image_link = $medium_image[0]; 
$html = '<img src="'.$medium_image_link.'" alt="" />';