2012-03-31 72 views
1

wordpress對圖片有很好的支持。PHP Wordpress動態自定義圖片尺寸

得到新的圖像尺寸,一個只想補充一些功能,如:

add_theme_support('post-thumbnails'); //thumnails 
set_post_thumbnail_size(200, 120, true); // Normal post thumbnails 
add_image_size('single-post-thumbnail', 400, 300,False); // single-post-test 
add_image_size('tooltip', 100, 100, true); // Tooltips thumbnail size 
/// and so on and so on 

我的問題是:

別人怎樣才能讓這些功能作用以動態的方式,這意味着那些大小會在上傳時計算?

例如 - 如果我上傳3000x4000像素的圖像 - 我想我的圖像尺寸是:

add_image_size('half', 50%, 350%, False); // Half the original 
add_image_size('third', 30%, 30%, true); // One Third the original 

有沒有辦法做到這一點?我可以在哪裏掛鉤? 這些圖像大小已用於許多功能註冊 - 有人可以想到一個優步 - 創造性的方式來實現嗎?

回答

1

您可以使用wp_get_attachment_image_src獲得一個附件的尺寸減小的圖像,你如果你只需要在你的functions.php文件中指定add_theme_support('post-thumbnails')然後在模板中執行以下操作:

$id = get_post_thumbnail_id($post->ID) 
$orig = wp_get_attachment_image_src($id) 
$half = wp_get_attachment_image_src($id, array($orig[1]/2, orig[2]/2)) 
$third = wp_get_attachment_image_src($id, array($orig[1]/3, orig[2]/3)) 
etc... 
+0

感謝半圖像的新圖像你的答案 。首先 - 它被用於插件 - 而不是主題。第二 - 如果我會使用這種方法 - 上傳時不會創建拇指,或者我錯了嗎? – 2012-03-31 10:10:04

+0

你也可以在插件中調用'wp_get_attachment_image_src'。是的,重新調整大小的圖像將在第一次調用該方法時創建,但我想您可以掛鉤到「add_attachment」並在原始上傳之後創建它們。 – 2012-03-31 10:44:13

+0

但可以有1000個原件 - 每個帖子可以有10個或20個... – 2012-04-01 09:52:22

2

或者你可以使用過濾器image_resize_dimensions

我已經安裝有奇怪的寬度和高度,像這樣

add_image_size('half', 101, 102); 

然後使用的過濾器,以僅當半圖像大小被調整大小

add_filter('image_resize_dimensions', 'half_image_resize_dimensions', 10, 6); 

function half_image_resize_dimensions($payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop){ 
    if($dest_w === 101){ //if half image size 
     $width = $orig_w/2; 
     $height = $orig_h/2; 
     return array(0, 0, 0, 0, $width, $height, $orig_w, $orig_h); 
    } else { //do not use the filter 
     return $payload; 
    } 
}