-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwp-image-optimiser.php
68 lines (49 loc) · 1.24 KB
/
wp-image-optimiser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
namespace WP_Image_Optimiser;
/*
Plugin Name: WP Image Optimiser
Plugin URI: https://github.com/jonmcpartland/wp-image-optimiser/
Description: Optimise images upon upload. Requires Imagick.
Version: 0.1.0
Author: Jon McPartland
Author URI: https://jon.mcpart.land
Textdomain: wp-image-optimiser
*/
if ( ! class_exists( '\\Imagick' ) ) {
return;
}
require_once __DIR__ . '/includes/Optimiser.php';
use ImagickException;
new class {
protected $optimiser;
protected static $allowedMimes = [
'image/jpeg',
'image/gif',
'image/png',
'image/bmp',
'image/tiff',
'image/x-icon',
];
public function __construct() {
\add_filter( 'wp_handle_upload_prefilter', [ $this, 'upload' ] );
$this->load();
}
public function upload( $file ) {
// bail if not an image
if ( ! in_array( $file['type'], static::$allowedMimes ) ) {
return $file;
}
try {
$this->optimiser->load( $file['tmp_name'], $file['name'] );
} catch ( ImagickException $e ) {
unset( $file['tmp_name'] );
return $file;
}
$this->optimiser->optimise()->save();
return $file;
}
protected function load() {
$settings = \apply_filters( 'wp_image_optimiser_settings', Optimiser::defaults() );
$this->optimiser = new Optimiser( $settings );
}
};