WordPress.org

Forums

Cache control headers for resized images (1 post)

  1. djquinn
    Member
    Posted 1 year ago #

    I have a function that resizes images on the fly in WordPress. I also have W3 Total Cache set up to add cache control to all my images, but the ones being resized by the function are served as private with no cache control.

    The function looks like this:

    public static function resize( $path, $max_width = null, $max_height = null, $crop = true, $args = '') {
    
        // determine base path for uploads
        $upload_dir = wp_upload_dir();
    
        // let's specify some common defaults
        $defaults = array(
            'quality' => 100,
            'suffix' => null,
            'uploads_url' => $upload_dir['baseurl'],
            'uploads_directory' => $upload_dir['basedir'],
            'crops_directory' => '/wpx/',
            'filetype' => null
        );
    
        // standard WP default arguments merge
        $parameters = wp_parse_args( $args, $defaults );
        extract( $parameters, EXTR_SKIP );
    
        // get the path
        $system_root = $_SERVER[ 'DOCUMENT_ROOT' ];
        $file_path = parse_url($path);
        $image = wp_get_image_editor($system_root.$file_path['path']);
    
        // only do stuff on success
        if ( ! is_wp_error( $image ) ) {
            // resize the image
            if ($max_width || $max_height) { $image->resize( $max_width, $max_height, $crop ); }
            // set the quality
            if ($parameters['quality']) $image->set_quality( $parameters['quality'] );
            // rotate the image
            if ($parameters['rotate']) $image->rotate( $parameters['rotate'] );
            // flip the image
            if ($parameters['flip']) $image->flip( true, false );
            // crop the image
            if ($parameters['crop']) $image->crop( $parameters['crop'] );
            // generate the filename
    
            $filename = $image->generate_filename($parameters['suffix'], $parameters['uploads_directory'].$parameters['crops_directory'], $parameters['filetype'] );
    
            // save the image
            $image_meta = $image->save($filename);
            // insert the URL path to the crop
            $image_meta['url'] = $parameters['uploads_url'].$parameters['crops_directory'].$image_meta['file'];
            // return the data
            return $image_meta;
        }
    }

    The website in question is http://dquinn.net. If you do a PageSpeedTest, you'll see it complains "Specify a cache validator" for all the images in the /wpx/ folder, which is where this function saves them.

    What am I doing wrong??

Topic Closed

This topic has been closed to new replies.

About this Topic