Sarathlal N

Adding custom image size for WordPress media Library

To add new custom image size for WordPress media gallery, we can use add_image_size() function.

<?php add_image_size( $name, $width, $height, $crop ); ?>

Example code in theme’s functions.php file

add_image_size( 'category-thumb', 300,160 ); // 300 pixels wide and 160 pixels height - resized
add_image_size( 'homepage-thumb', 220, 180, true ); // 220 pixels wide and 180 pixels height - cropped

Different crop modes

  1. Set the image size by resizing the image proportionally (without distorting it):

     add_image_size( 'custom-size', 220, 180 ); // 220 pixels wide by 180 pixels tall, soft proportional crop mode
    
  2. Set the image size by cropping the image (not showing part of it):

     add_image_size( 'custom-size', 220, 180, true ); // 220 pixels wide by 180 pixels tall, hard crop mode
    
  3. Set the image size by cropping the image and defining a crop position:

     add_image_size( 'custom-size', 220, 220, array( 'left', 'top' ) ); // Hard crop left top
    

Using the New Image Sizes in WordPress

  1. For Featured Images

     <?php 
     if ( has_post_thumbnail() ) { 
      the_post_thumbnail( 'your-custom-size-name' ); 
     }
     ?>
    
  2. For General Media (PHP/Templates)

     <?php echo wp_get_attachment_image( $post-id, 'your-custom-size-name' ); ?>
    

Looking for a skilled WordPress/WooCommerce developer? I'm currently available for freelance, contract, or full-time remote opportunities! Let's create something amazing together. Send me a quick message, and I'll respond within 24 hours!

Recent Posts

  1. Automating Code Linting with GitHub Actions for WordPress Plugins
  2. Comprehensive Guide to Linting PHP, JavaScript, and CSS in WordPress Plugins Using Composer
  3. The Ultimate Guide to Indexing in Database Design
  4. Understanding 'update_meta_cache' in WordPress - When to Use It, When Not to, and Its Impact on Database Queries
  5. A Guide to Configuring JavaScript and SCSS Paths in WordPress Plugins with @wordpress/scripts

Your Questions / Comments

If you found this article interesting, found errors, or just want to discuss about it, please get in touch.