當我上傳精選圖片時,我想給它一個「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;
}