Skip to content

Instantly share code, notes, and snippets.

@wpfangirl
Last active August 24, 2024 19:29
Show Gist options
  • Save wpfangirl/73436d26d7de3b82e66a9c4036d8490f to your computer and use it in GitHub Desktop.
Save wpfangirl/73436d26d7de3b82e66a9c4036d8490f to your computer and use it in GitHub Desktop.
Use oembed_dataparse to calculate padding for responsive embeds, with simplified CSS
/**
* Add to your stylesheet if it isn't there
*/
.wp-embed-responsive {
position:relative;
margin-bottom: 20px;
}
.wp-embed-responsive > iframe{
bottom:0;
height:100%;
left:0;
position:absolute;
right:0;
top:0;
width:100%;
max-width:100%;
}
<?php
/**
* Responsive embed padding calculation adapted from @mayasol
* https://developer.wordpress.org/reference/hooks/oembed_dataparse/
* Add this to your functions.php file or wherever you're putting additional PHP
*/
add_filter( 'oembed_dataparse', 'wrap_oembed_dataparse', 99, 4 );
function wrap_oembed_dataparse($return, $data, $url) {
$mod = '';
$ratio = '';
$padding = '';
if ( isset($data->width) && isset($data->height) ) {
$mod = 'wp-embed-aspect-' . $data->width . '-' . $data->height;
$ratio = round($data->height/$data->width, 4);
$padding = ( $ratio * 100 );
}
return '<div class="wp-embed-responsive ' . $mod . '"><span style="display:block; padding-top: ' . $padding . '%";></span>' . $return . '</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment