2012-11-08 39 views
0

當我上傳精選圖片時,我想給它一個「100%」的寬度,但只有當它超過1170像素。如果寬度在1170像素和770像素之間,我希望寬度爲「770像素」,否則寬度不會改變。如何在WordPress中編寫自定義函數?

到目前爲止,這段代碼是做我想要的東西:

if (intval($width) >= 1170) { 
     $hwstring = 'width=100%'; 
    } elseif ((intval($width) < 1170) && (intval($width) >= 770)) { 
     $hwstring = 'width=770px'; 
    } else { 
     $hwstring = image_hwstring($width, 0); 
    }; 

不過,我已經修改了文件忽略原始的「WP-包括」文件夾,這顯然是不這樣做的正確方法裏面。那麼,如何創建一個能夠在不修改現有Wordpress代碼的情況下執行相同操作的函數呢?

function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') { 

$html = ''; 
$image = wp_get_attachment_image_src($attachment_id, $size, $icon); 
if ($image) { 
    list($src, $width, $height) = $image; 
    $hwstring = image_hwstring($width, $height); 
    if (is_array($size)) 
     $size = join('x', $size); 
    $attachment =& get_post($attachment_id); 
    $default_attr = array(
     'src' => $src, 
     'class' => "attachment-$size", 
     'alt' => trim(strip_tags(get_post_meta($attachment_id, '_wp_attachment_image_alt', true))), // Use Alt field first 
     'title' => trim(strip_tags($attachment->post_title)), 
    ); 
    if (empty($default_attr['alt'])) 
     $default_attr['alt'] = trim(strip_tags($attachment->post_excerpt)); // If not, Use the Caption 
    if (empty($default_attr['alt'])) 
     $default_attr['alt'] = trim(strip_tags($attachment->post_title)); // Finally, use the title 

    $attr = wp_parse_args($attr, $default_attr); 
    $attr = apply_filters('wp_get_attachment_image_attributes', $attr, $attachment); 
    $attr = array_map('esc_attr', $attr); 

    if (intval($width) >= 1170) { 
     $hwstring = 'width=100%'; 
    } elseif ((intval($width) < 1170) && (intval($width) >= 770)) { 
     $hwstring = 'width=770px'; 
    } else { 
     $hwstring = image_hwstring($width, 0); 
    }; 

    $html = rtrim("<img $hwstring"); 
    foreach ($attr as $name => $value) { 
     $html .= " $name=" . '"' . $value . '"'; 
    } 
    $html .= ' />'; 
} 

return $html; 
} 

回答

0

遺憾的是沒有任何掛鉤您使用要做到這一點正是在這功能,但你可以自己構建它,而無需修改核心WordPress的文件(你不想做,免得你覆蓋您升級時的自定義代碼)。我很驚訝wp_get_attachment_image_src()函數沒有通過過濾器傳遞返回值來完成你正在談論的內容。

如果你看看這個函數的頂部,它得到的和陣列的$src, $width, $height致電$image = wp_get_attachment_image_src($attachment_id, $size, $icon);你可以讓此相同稱自己並構建自定義的寬度 - 基本複製功能到定製版本的functions.php或一個custom functions plugin

如果您想要在將來的版本中添加此功能,您可以在 http://core.trac.wordpress.org/newticket處創建新票據。加入將是 wp_get_attachment_image_src()上線515(的WP目前主幹版本):

return apply_filters('wp_get_attachment_image_src', array($src, $width, $height), $attachment_id, $size, $icon); 

編輯:門票已經exists,補丁是有點怪異,我提交a new one但任何保證到什麼時候它會進入,如果它被批准..

相關問題