0

当我上传特色图片时,我想给它“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;
}
4

1 回答 1

0

不幸的是,在该函数中没有任何钩子供您使用,但您可以自己构建它而无需修改核心 Wordpress 文件(您不想这样做,以免在升级时覆盖您的自定义代码) . 我有点惊讶该wp_get_attachment_image_src()函数没有通过过滤器传递返回值来完全按照您的意思行事。

如果您查看此函数的顶部,它会$src, $width, $height通过调用获取 and 数组$image = wp_get_attachment_image_src($attachment_id, $size, $icon);您可以自己进行相同的调用并构建自定义宽度 - 基本上将函数复制到 functions.php 中的自定义版本或自定义函数插件中。

您可以在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 );

编辑:票已经存在,补丁有点奇怪,我提交了一个新的,但不能保证如果它被批准它什么时候会进去..

于 2012-11-08T06:54:45.323 回答