当我上传特色图片时,我想给它“100%”的宽度,但前提是它超过 1170 像素。如果宽度在 1170px 和 770px 之间,我希望它得到一个“770px”的宽度,否则宽度不会改变。
到目前为止,这段代码正在做我想要的:
if (intval($width) >= 1170) {
$hwstring = 'width=100%';
} elseif ( (intval($width) < 1170) && (intval($width) >= 770) ) {
$hwstring = 'width=770px';
} else {
$hwstring = image_hwstring($width, 0);
};
但是我已经修改了“wp-includes”文件夹中的 media.php 文件,这显然不是正确的方法。那么如何在不修改现有 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;
}