Using WordPress ‘image_send_to_editor’ PHP filter

The image_send_to_editor WordPress PHP Filter modifies the image HTML markup to send to the editor when inserting an image.

Usage

add_filter('image_send_to_editor', 'your_custom_function', 10, 9);
function your_custom_function($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  // your custom code here
  return $html;
}

Parameters

  • $html string: The image HTML markup to send.
  • $id int: The attachment ID.
  • $caption string: The image caption.
  • $title string: The image title.
  • $align string: The image alignment.
  • $url string: The image source URL.
  • $size string|int[]: Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).
  • $alt string: The image alternative, or alt, text.
  • $rel string: The image rel attribute.

More information

See WordPress Developer Resources: image_send_to_editor

Examples

Add a custom CSS class to image

Add a custom CSS class to the image markup.

add_filter('image_send_to_editor', 'add_custom_class', 10, 9);
function add_custom_class($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  $custom_class = 'my-custom-class';
  $html = str_replace('<img', '<img class="' . $custom_class . '"', $html);
  return $html;
}

Add a data attribute to the image

Add a data attribute named ‘data-custom’ with a value ‘example-value’ to the image markup.

add_filter('image_send_to_editor', 'add_data_attribute', 10, 9);
function add_data_attribute($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  $html = str_replace('<img', '<img data-custom="example-value"', $html);
  return $html;
}

Change the image source URL

Replace the image source URL with a custom URL.

add_filter('image_send_to_editor', 'change_image_url', 10, 9);
function change_image_url($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  $custom_url = 'https://example.com/custom-image.jpg';
  $html = str_replace($url, $custom_url, $html);
  return $html;
}

Add a custom wrapper around the image

Wrap the image with a custom div element.

add_filter('image_send_to_editor', 'add_custom_wrapper', 10, 9);
function add_custom_wrapper($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  $html = '<div class="custom-wrapper">' . $html . '</div>';
  return $html;
}

Remove the image alignment

Remove the alignment attribute from the image markup.

add_filter('image_send_to_editor', 'remove_image_alignment', 10, 9);
function remove_image_alignment($html, $id, $caption, $title, $align, $url, $size, $alt, $rel) {
  $html = preg_replace('/class=".?align[a-zA-Z]\s/', 'class="', $html); 
  return $html; 
}