2012-11-08 40 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但任何保证到什么时候它会进入,如果它被批准..

相关问题