Last active
August 31, 2020 18:34
-
-
Save cibulka/8e2bf16b0f55779af590472ae1bf9239 to your computer and use it in GitHub Desktop.
Hardcoded `width` and `height` to Wordpress image functions is INSANE! This is my current sollution to the problem, that removes `hwstring` and keeps `srcset`, `sizes` and other responsive image attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Picture { | |
public function init_remove_hwstring() { | |
add_filter('image_downsize', array($this, 'remove_hw_from_downsize'), 10, 3); | |
add_filter('wp_get_attachment_image_attributes', array($this, 'add_srcset_sizes'), 10, 3); | |
} | |
public function add_srcset_sizes($attrs, $attachment, $size) { | |
$meta = wp_get_attachment_metadata($attachment->ID); | |
if (empty($meta['sizes'])) { return $attrs; } | |
// Srcset | |
$def_width = false; | |
$srcset = []; | |
remove_filter('image_downsize', array($this, 'remove_hw_from_downsize'), 10, 3); | |
foreach ($meta['sizes'] as $size_name => $data) { | |
$def_width = $size_name === $size ? $data['width'] : $def_width; | |
$srcset[] = \Cibulka::Base('WP_Utils')->get_image_url($attachment->ID, $size) . ' ' . $data['width'] . 'w'; | |
} | |
add_filter('image_downsize', array($this, 'remove_hw_from_downsize'), 10, 3); | |
$attrs['srcset'] = implode(', ', $srcset); | |
// Sizes | |
$attrs['sizes'] = sprintf('(max-width: %1$dpx) 100vw, %1$dpx', $def_width); | |
return $attrs; | |
} | |
/** | |
* @link https://wordpress.stackexchange.com/a/29886/28718 | |
*/ | |
public function remove_hw_from_downsize($result, $id, $size) { | |
if (!wp_attachment_is_image($id)) { | |
return false; | |
} | |
$img_url = wp_get_attachment_url($id); | |
$is_intermediate = false; | |
$img_url_basename = wp_basename($img_url); | |
// try for a new style intermediate size | |
if ($intermediate = image_get_intermediate_size($id, $size)) { | |
$img_url = str_replace($img_url_basename, $intermediate['file'], $img_url); | |
$is_intermediate = true; | |
} elseif ( $size == 'thumbnail' ) { | |
// Fall back to the old thumbnail | |
if (($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file)) { | |
$img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url); | |
$is_intermediate = true; | |
} | |
} | |
// We have the actual image size, but might need to further constrain it if content_width is narrower | |
if ($img_url) { | |
return array( $img_url, 0, 0, $is_intermediate); | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment