• Resolved delaitec

    (@delaitec)


    Hello.

    I believe everyone here likes to save space on hosting.

    To reduce the amount of unnecessary images that take up space, I’m looking for a way to create the thumbails only for the images featured in the posts.

    I found in this guide a part of the solution:
    https://www.gavsblog.com/blog/regenerate-wordpress-media-image-sizes-programmatically

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    // Put the function in a class to make it more extendable
    class GB_regen_media {
        public function gb_regenerate($imageId) {
            $imagePath = wp_get_original_image_path($imageId);
    
            if ($imagePath && file_exists($imagePath)) {
    wp_generate_attachment_metadata($imageId, $imagePath);
            }
        }
    }
    
    // Add a load function
    function gb_regen_load() {
        // Instantiate the class
        $gb_regen_media = new GB_regen_media();
    
        // Set the image Id
        $imageId = 1;
    
        // You can get the image Id from the url of the media screen
        $gb_regen_media-
    >gb_regenerate($imageId);
    }
    
    // Load after WordPress has finished loading
    add_action('init', 'gb_regen_load');

    However, it creates the image using the sizes defined in the theme.

    And as I want to prevent copies from being created with each new image uploaded,
    I turned off automatic creation by setting everything to “0”.

    Researching the function used in the above tip:
    wp_generate_attachment_metadata

    I saw that it generates the copies based on the dimensions defined in the theme:
    https://www.ads-software.com/support/article/settings-media-screen/

    But as I explained above, I disabled creation there, to avoid unnecessary images.

    Can anyone give me a suggestion to create this thumbnail so that I set the size myself in the function?

    because as I said, it is not possible to use the theme size as it is disabled.

    Grateful.

Viewing 7 replies - 1 through 7 (of 7 total)
  • I saw that it generates the copies based on the dimensions defined in the theme:
    https://www.ads-software.com/support/article/settings-media-screen/

    That’s not the “dimensions defined in the theme”. That’s WordPress’ default dimensions.

    The dimensions defined by the theme will be defined in the theme’s own code, likely in the theme’s functions.php file. But note that plugins may also define their own dimensions, again, in the individual plugin’s own code.

    Thread Starter delaitec

    (@delaitec)

    Hello,

    Thank you for your help.

    I use a plugin: “ThumbPress – Stop Generating Unnecessary Thumbnails
    to disable all custom sizes, both native to wordpress and created by the theme.

    So that when sending images no additional images are created.

    Now,
    what I need is to create 2 custom sizes “only” when an image is set as a featured image for a post.

    This way there will only be copies of images for the highlighted images.

    I managed to develop this code, but it does not work.

    /* Create thumbnails */
    function create_thumbnail_f() {
    	
    	global $post;
    	$image_id = get_post_thumbnail_id($post->ID);
    	$width = '150';
    	$height = '150';
    	$crop = '';
    	
        // Temporarily create an image size
        $size_id = 'lazy_' . $width . 'x' .$height . '_' . ((string) $crop);
        add_image_size($size_id, $width, $height, $crop);
    
        // Get the attachment data
        $meta = wp_get_attachment_metadata($image_id);
    
        // If the size does not exist
        if(!isset($meta['sizes'][$size_id])) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
    
            $file = get_attached_file($image_id);
            $new_meta = wp_generate_attachment_metadata($image_id, $file);
    
            // Merge the sizes so we don't lose already generated sizes
            $new_meta['sizes'] = array_merge($meta['sizes'], $new_meta['sizes']);
    
            // Update the meta data
            wp_update_attachment_metadata($image_id, $new_meta);
        }
    
        // Fetch the sized image
        $sized = wp_get_attachment_image_src($image_id, $size_id);
    
        // Remove the image size so new images won't be created in this size automatically
        remove_image_size($size_id);
        return $sized;
    }
    /* Create when publish a post */
    add_action('new_to_publish', 'create_thumbnail_f');
    add_action('pending_to_publish', 'create_thumbnail_f');
    add_action('future_to_publish', 'create_thumbnail_f');

    Could anyone explain what might be missing?

    Thread Starter delaitec

    (@delaitec)

    The first code I posted works, but only if I set the ID of the image I want to create copies of.

    But it doesn’t create when setting the thumbnail.

    Ideally, this code would get the id of the post I just saved, and then create copies of the highlighted image of it.

    • This reply was modified 2 years ago by Yui.
    • This reply was modified 2 years ago by bcworkz. Reason: format fixed
    Moderator bcworkz

    (@bcworkz)

    You can remove sizes added by themes and plugins with remove_image_size(). You must do so after they’ve initially been added. Sizes are typically added through the “after_setup_theme” action. You can remove from the same action as long as you hook with a larger priority arg.

    However you cannot remove the default sizes. I suggest you define the default sizes as desired. If you don’t need all 3, set some to be very small and just don’t use them. They won’t take up that much space.

    This will still cause the default sizes to be created for every image upload, regardless of whether it’ll be a featured image or not. It’s impractical to determine an image’s future use as featured at the time it is uploaded. IMO, it’s not worth worrying about. Removing additional defined sizes will give you the biggest gains is server space utilization.

    Thread Starter delaitec

    (@delaitec)

    Hello.

    Thanks a lot for the help.

    See, forget the question about disabling other sizes.
    I need to do this, and I already managed to use the tumbpress plugin, that is, at the moment no additional images are being created.

    What I need at this point is:
    Create copies in sizes 150×150 and 300×300 only when defining the image as a featured image of a post.

    Thread Starter delaitec

    (@delaitec)

    I try this code:

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    // Put the function in a class to make it more extendable
    class GB_regen_media {
        public function gb_regenerate($imageId) {
    // Defining custom size
    add_image_size( 'imagem-media', 300, 300 ); 	
            $imagePath = wp_get_original_image_path($imageId);
            if ($imagePath && file_exists($imagePath)) {
                wp_generate_attachment_metadata($imageId, $imagePath);
            }
        }
    }
    
    function cria_thumbnail_da_imagemdestacada_f() {  
    
    // Add a load function
    function gb_regen_load() {
    global $post;	
        // Instantiate the class
        $gb_regen_media = new GB_regen_media();
        // Set the image Id
        $imageId = get_post_thumbnail_id($post->ID); 	
        // You can get the image Id from the url of the media screen
        $gb_regen_media->gb_regenerate($imageId);
    }
    // Load after WordPress has finished loading
    add_action('init', 'gb_regen_load');
    }
    
    // Create Thumbnail when publishing a post
    add_action('new_to_publish', 'cria_thumbnail_da_imagemdestacada_f');
    add_action('pending_to_publish', 'cria_thumbnail_da_imagemdestacada_f');
    add_action('future_to_publish', 'cria_thumbnail_da_imagemdestacada_f');

    But aparently the:
    add_action('init', 'gb_regen_load');
    cant stay inside a function.

    Someone can help with this last code?
    I feel like I’m almost there

    Thread Starter delaitec

    (@delaitec)

    SOLVED ??

    Thanks thanks to everyone!

    // Thumbnail Images - Defining, Activating and Removing Dimensions.
    // Thanks: https://artneo.com.br/como-remover-tamanhos-imagens-wordpress/
    
    When the image is uploaded, only the 150x150 size is created
    function artneo_image_sizes(){
    	update_option( 'thumbnail_size_w', 150 );
    	update_option( 'thumbnail_size_h', 150 );	
    	//update_option( 'thumbnail_crop', ['center', 'center'] );	
    	update_option( 'medium_size_w', 0 );
    	update_option( 'medium_size_h', 0 );
    	update_option( 'medium_large_size_w', 0 );
    	update_option( 'medium_large_size_h', 0 );
    	update_option( 'large_size_w', 0 );
    	update_option( 'large_size_h', 0 );
    	//add_image_size( 'featured', 1280, 720, ['center', 'top']);
    	//add_image_size( 'full', 1920, 1080, ['center', 'center']);
    	remove_image_size( '1536x1536' );
    	remove_image_size( '2048x2048' );
    }
    add_action('after_setup_theme', 'artneo_image_sizes');
    
    /* Creating the thumbnail 300x300 only when an image is set as a featured image */
    // Thanks: https://www.gavsblog.com/blog/regenerate-wordpress-media-image-sizes-programmatically
    
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    // Put the function in a class to make it more extendable
    class GB_regen_media{
    	public function gb_regenerate($imageId){
    		add_image_size( 'imagem-media', 300, 300 );		// Defining dimensions to be created on save.
            $imagePath = wp_get_original_image_path($imageId);
            if ($imagePath && file_exists($imagePath)){		// If the image exists.
    			wp_generate_attachment_metadata($imageId, $imagePath);		// Create the thumbnail.
            }
        }
    }
    	
    // Add a load function
    function gb_regen_load(){
    	global $post;
        // Instantiate the class
        $gb_regen_media = new GB_regen_media();
        // Set the image Id
        $imageId = get_post_thumbnail_id($post->ID); 	
        // You can get the image Id from the url of the media screen
        $gb_regen_media->gb_regenerate($imageId);
    }
    
    /* Create Thumbnail when publishing a post */
    add_action('new_to_publish', 'gb_regen_load');
    add_action('pending_to_publish', 'gb_regen_load');
    add_action('future_to_publish', 'gb_regen_load');  
    /* Create Thumbnail when saving post */
    add_action('save_post', 'gb_regen_load');

    ??

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Create thumbnail for featured images only’ is closed to new replies.