|
<?php |
|
/** |
|
* Plugin Name: WPP Better Image Sizes |
|
* Plugin URI: https://github.com/joemcgill/wpp-better-image-sizes |
|
* Description: This is a WordPress Plugin that improves the default sizes attribute calculation for images. |
|
* Version: 0.1 |
|
* Author: Joe McGill |
|
* Author URI: https://joemcgill.net/ |
|
* License: GPL2 |
|
*/ |
|
|
|
namespace WPP_Better_Image_Sizes; |
|
|
|
use \WP_HTML_Tag_Processor; |
|
|
|
// If this file is called directly, abort. |
|
if ( ! defined( 'WPINC' ) ) { |
|
die; |
|
} |
|
|
|
add_filter( 'render_block_core/image', __NAMESPACE__ . '\\add_sizes_attribute', 10, 3 ); |
|
add_filter( 'render_block_core/cover', __NAMESPACE__ . '\\add_sizes_attribute', 10, 3 ); |
|
|
|
/** |
|
* Filter the sizes attribute for images to improve the default calculation. |
|
* |
|
* @param string $content The block content about to be rendered. |
|
* @param array $parsed_block The parsed block. |
|
* @param \WP_Block $block The block object. |
|
* @return string The updated block content. |
|
*/ |
|
function add_sizes_attribute( $content, $parsed_block, $block ) { |
|
|
|
$tags = new WP_HTML_Tag_Processor( $content ); |
|
$image = $tags->next_tag( 'img' ); |
|
$layout = wp_get_global_settings( array( 'layout' ) ); |
|
|
|
// Only update the markup if an image is found and we have layout settings. |
|
if ( $image && isset( $layout['wideSize'] ) && $layout['contentSize'] ) { |
|
|
|
$align = $parsed_block['attrs']['align'] ?? null; |
|
|
|
// @todo: Calculate padding from theme settings. Use 2rem as an example for now. |
|
$padding = '2rem'; |
|
|
|
// Handle different alignment use cases. |
|
switch ($align) { |
|
case 'full': |
|
$isRootPaddingAware = wp_get_global_settings( array( 'useRootPaddingAwareAlignments' ) ); |
|
|
|
$sizes = $isRootPaddingAware ? '100vw' : sprintf( 'calc(100vw - %1$s)', $padding ); |
|
|
|
break; |
|
|
|
case 'wide': |
|
$sizes = sprintf( '(max-width: calc(%1$s + %2$s)) calc(100vw - %2$s), %1$s', $layout['wideSize'], $padding ); |
|
break; |
|
|
|
// @todo: handle left/right alignments. |
|
case 'left': |
|
case 'right': |
|
// $width = $parsed_block['attrs']['width'] ?? null; |
|
// $sizes = $width ? sprintf( '(max-width: %1$s) 100vw, %1$s', $width ) : null; |
|
// break; |
|
|
|
default: |
|
$sizes = sprintf( '(max-width: calc(%1$s + %2$s)) calc(100vw - %2$s), %1$s', $layout['contentSize'], $padding ); |
|
break; |
|
} |
|
|
|
if ( $sizes ) { |
|
$tags->set_attribute( 'sizes', $sizes ); |
|
} |
|
|
|
$content = $tags->get_updated_html(); |
|
} |
|
|
|
return $content; |
|
} |