Using WordPress ‘image_editor_save_pre’ PHP filter

The image_editor_save_pre WordPress PHP Filter allows you to modify the image editor instance before it’s streamed to the browser.

Usage

add_filter('image_editor_save_pre', 'your_custom_function', 10, 2);

function your_custom_function($image, $attachment_id) {
    // your custom code here
    return $image;
}

Parameters

  • $image (WP_Image_Editor) – The image editor instance.
  • $attachment_id (int) – The attachment post ID.

More information

See WordPress Developer Resources: image_editor_save_pre

Examples

Add watermark to image

Add a watermark to the image before it’s streamed to the browser.

add_filter('image_editor_save_pre', 'add_watermark_to_image', 10, 2);

function add_watermark_to_image($image, $attachment_id) {
    $watermark_path = '/path/to/watermark.png';
    $image->watermark($watermark_path, 100, 100, 50);
    return $image;
}

Convert image to grayscale

Convert the image to grayscale before streaming to the browser.

add_filter('image_editor_save_pre', 'convert_image_to_grayscale', 10, 2);

function convert_image_to_grayscale($image, $attachment_id) {
    $image->apply_filter('IMG_FILTER_GRAYSCALE');
    return $image;
}

Resize image

Resize the image to specific dimensions before streaming to the browser.

add_filter('image_editor_save_pre', 'resize_image', 10, 2);

function resize_image($image, $attachment_id) {
    $width = 300;
    $height = 200;
    $image->resize($width, $height, false);
    return $image;
}

Rotate image

Rotate the image by a specific angle before streaming to the browser.

add_filter('image_editor_save_pre', 'rotate_image', 10, 2);

function rotate_image($image, $attachment_id) {
    $angle = 90;
    $image->rotate($angle);
    return $image;
}

Flip image horizontally

Flip the image horizontally before streaming to the browser.

add_filter('image_editor_save_pre', 'flip_image_horizontally', 10, 2);

function flip_image_horizontally($image, $attachment_id) {
    $image->flip(false, true);
    return $image;
}