Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* If inserting a gif always place the full size image
*
* @link https://whoischris.com/code-sample-keep-gif-animation-when-adding-media-to-post-content-in-wordpress/
*
* @param string $html
* @param int $send_id
* @param array $attachment
*
* @return string
*/
add_filter( 'media_send_to_editor', 'full_size_only_gif', 10, 3 );
function full_size_only_gif( $html, $send_id, $attachment ) {
$meta = wp_get_attachment_metadata( $send_id );
if ( ! isset( $meta['file'], $meta['width'], $meta['height'] ) ) {
return $html;
}
$parts = explode( '.', $meta['file'] );
$ext = strtolower( $parts[ \count( $parts ) - 1 ] );
if ( $ext !== 'gif' ) {
return $html;
}
$new_html = '';
$xml = simplexml_load_string( $html );
foreach( $xml->attributes() as $a => $b ) {
switch ( $a ) {
case 'src' :
$new_html .= ' src="' . wp_get_attachment_image_url( $send_id, 'full' ) . '"';
break;
case 'width' :
$new_html .= " width=\"{$meta['width']}\"";
break;
case 'height' :
$new_html .= " height=\"{$meta['height']}\"";
break;
default :
$new_html .= " $a=\"$b\"";
}
}
$new_html = "<img $new_html />";
return $new_html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment