Reputation: 537
I'm trying to implement two PHP functions to disable image resizing for gif images on WordPress that are animated. There's a solution to disable the upload if the file MIME type is gif, but this isn't enough. A gif can also be just a image. So I thought I combine it with a PHP script that checks if a file is an animated gif or not by using this solution. This seems to work if I lets say echo this function on my theme file, but doesn't seem to function if I use it inside functions.php.
/**
* Detects animated GIF from given file pointer resource or filename.
*
* @param resource|string $file File pointer resource or filename
* @return bool
*/
function is_animated_gif($file)
{
$fp = null;
if (is_string($file)) {
$fp = fopen($file, "rb");
} else {
$fp = $file;
/* Make sure that we are at the beginning of the file */
fseek($fp, 0);
}
if (fread($fp, 3) !== "GIF") {
fclose($fp);
return false;
}
$frames = 0;
while (!feof($fp) && $frames < 2) {
if (fread($fp, 1) === "\x00") {
/* Some of the animated GIFs do not contain graphic control extension (starts with 21 f9) */
if (fread($fp, 1) === "\x21" || fread($fp, 2) === "\x21\xf9") {
$frames++;
}
}
}
fclose($fp);
return $frames > 1;
}
function disable_upload_sizes( $sizes, $metadata ) {
$uploads = wp_upload_dir();
$upload_path = $uploads['baseurl'];
$relative_path = $metadata['file'];
$file_url = $upload_path . $relative_path;
if( is_animated_gif( $file_url ) ) {
$sizes = array();
}
// Return sizes you want to create from image (None if image is gif.)
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'disable_upload_sizes', 10, 2);
What am I'm doing wrong over here that this isn't functioning?
Upvotes: 2
Views: 635
Reputation: 65254
your code works... but there's an error on the $file_url
.
It should be $file_url = $upload_path . '/' . $relative_path;
Upvotes: 4