PHP Wordpress dynamic custom image sizes

◇◆丶佛笑我妖孽 提交于 2019-12-24 15:45:55

问题


wordpress has a good support for images in general.

to get new image sizes, one would just add some functions like :

add_theme_support( 'post-thumbnails' ); //thumnails
set_post_thumbnail_size( 200, 120, true ); // Normal post thumbnails
add_image_size( 'single-post-thumbnail', 400, 300,False ); // single-post-test
add_image_size( 'tooltip', 100, 100, true ); // Tooltips thumbnail size
/// and so on and so on 

my question is :

How can someone make those functions act in a dynamic manner , meaning that those sizes will be calculated on upload ?

for example - If I upload an image of 3000x4000 px - I would like my image sizes to be :

 add_image_size( 'half', 50%, 350%, False ); // Half the original
 add_image_size( 'third', 30%, 30%, true ); // One Third the original

Is there a way to do that ? where can I hook for that ? Those image sizes are used registered in many functions - Can someone think of an Uber-creative way to achieve that ?


回答1:


You can use wp_get_attachment_image_src to get downsized images of an attachement, in you case you only need to specify add_theme_support( 'post-thumbnails' ) in your functions.php file then in your template do the following:

$id = get_post_thumbnail_id($post->ID)
$orig = wp_get_attachment_image_src($id)
$half = wp_get_attachment_image_src($id, array($orig[1] / 2, orig[2] / 2))
$third = wp_get_attachment_image_src($id, array($orig[1] / 3, orig[2] / 3))
etc...



回答2:


Or you could use the filter image_resize_dimensions.

I have setup a new image with a strange width and height like so

add_image_size('half', 101, 102);

Then used the filter to half the image only when the half image size is being resized

add_filter( 'image_resize_dimensions', 'half_image_resize_dimensions', 10, 6 );

function half_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ){
    if($dest_w === 101){ //if half image size
        $width = $orig_w/2;
        $height = $orig_h/2;
        return array( 0, 0, 0, 0, $width, $height, $orig_w, $orig_h );
    } else { //do not use the filter
        return $payload;
    }
}


来源:https://stackoverflow.com/questions/9952360/php-wordpress-dynamic-custom-image-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!