PHP Wordpress dynamic custom image sizes

2019-08-15 09:09发布

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 ?

2条回答
倾城 Initia
2楼-- · 2019-08-15 09:51

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...
查看更多
神经病院院长
3楼-- · 2019-08-15 09:54

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;
    }
}
查看更多
登录 后发表回答