Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active January 16, 2020 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/ad6f7eec12e2c43b8065a63c3ac43aff to your computer and use it in GitHub Desktop.
Save wpmudev-sls/ad6f7eec12e2c43b8065a63c3ac43aff to your computer and use it in GitHub Desktop.
[Smush] - Fix srcset image sizes for better rendering
<?php
/**
* Plugin Name: [Smush] - Fix srcset image sizes for better rendering
* Plugin URI: https://premium.wpmudev.org/
* Description: Extend existing functionality of Smush to provide appropriate responsive image sizes (as of 3.2.4)
* Author: Alessandro Kaounas @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WPMUDEV_Smush_CDN_Sizes' ) ) {
class WPMUDEV_Smush_CDN_Sizes {
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Smush_CDN_Sizes();
}
return self::$_instance;
}
private function __construct() {
if ( class_exists( 'WP_Smush_Settings' ) ) {
$this->settings = WP_Smush_Settings::get_instance();
} elseif ( class_exists( '\\Smush\\Core\\Settings' ) ) {
$this->settings = \Smush\Core\Settings::get_instance();
} else {
return;
}
$this->init();
}
private function init(){
add_filter( 'wp_calculate_image_sizes', array( $this, 'wpmudev_update_image_sizes' ), 20, 5 );
}
public function wpmudev_update_image_sizes( $sizes, $size ) {
// Get maximum content width.
$content_width = $this->max_content_width();
if ( is_array( $size ) && $size[0] < $content_width ) {
return $sizes;
}
return sprintf( '(max-width: %1$dpx) 100vw, 100vw', $content_width );
}
private function max_content_width() {
// Get global content width (if content width is empty, set 1900).
$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : 1900;
// Check to see if we are resizing the images (can not go over that value).
$resize_sizes = $this->settings->get_setting( WP_SMUSH_PREFIX . 'resize_sizes' );
if ( isset( $resize_sizes['width'] ) && $resize_sizes['width'] < $content_width ) {
return $resize_sizes['width'];
}
// Just in case something goes wrong with the above checks.
if ( ! $content_width ) {
$content_width = 1900;
}
return $content_width;
}
}
if ( ! function_exists( 'WPMUDEV_Smush_CDN_Sizes' ) ) {
function WPMUDEV_Smush_CDN_Sizes() {
return WPMUDEV_Smush_CDN_Sizes::get_instance();
};
add_action( 'plugins_loaded', 'WPMUDEV_Smush_CDN_Sizes', 99 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment