add_image_size() to crop images into squares?

So I know about setting custom images with add_image_size('name',X,Y,Crop?) which is cool but I need to build something that will crop images, regardless of their size, into squares.

Basically, I want to make sure the user’s uploaded images will always be squares.

Related posts

Leave a Reply

2 comments

  1. If you pass true for the last $crop argument then so called “hard” crop mode is used. This will make WP produce results at exact size specified, except few edge cases (if image uploaded is smaller than specified size for example).

    Note that original image is still retained as is. If you need to actually modify originals as well — that is out of what WP native sizes functionality is intended for, will have to do that with custom code.

  2. I think a lot of theme development is getting away from using add_image_size because WordPress makes way to many images. So rather than doing it that way, you can use a plugin or even a plugin that will integrate into your theme. Here is a good one that is easy to use

    https://github.com/sy4mil/Aqua-Resizer

    I think this is a better way to go than doing the add_image_size. from the script, you just call whatever size and shape you will need.

    For example. Lets say you need an image that is 125 x 125 which would give you a nice square. You could do something like this inside the loop.

     $thumb = get_post_thumbnail_id();
     $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use    "large" or "medium" if the images too big)
     $image = aq_resize( $img_url, 125, 125, true ); //resize & crop the image
    
     ?>
    
     <article <?php post_class()?> id="post-<?php the_ID(); ?>">
    
    <?php if($image) : ?>
        <img src="<?php echo $image ?>"/>
    <?php endif; ?>
    

    That would take the featured image of the post and crop the image into a 125 x 125 sqaure and echo out the image.

    You can see more examples on this page