当我上传精选图片时,我想给它一个“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;
}