Skip to content

Instantly share code, notes, and snippets.

@monkishtypist
Created October 7, 2018 17:52
Show Gist options
  • Save monkishtypist/f55bde80ca5696fe07abdb4f381e4598 to your computer and use it in GitHub Desktop.
Save monkishtypist/f55bde80ca5696fe07abdb4f381e4598 to your computer and use it in GitHub Desktop.
Add Bootstrap image classes to WordPress media attachments
/**
* Add the following to your theme's `functions.php` to automatically add `img-fluid` class
* to all images inserted using the "Add Media" upload button in WordPress editor.
*/
if ( ! function_exists( 'add_bootstrap_class_to_images' ) ) {
function add_bootstrap_class_to_images( $html, $attachment_id, $attachment ) {
$img_element = "/<img[^>]*>/";
$found = preg_match( $img_element, $html, $image );
// If no image, do nothing
if ( $found <= 0)
return $html;
$image = $image[0];
if ( strstr( $image, "class=\"" ) !== FALSE ) { // If image already has class defined inject it to attribute
$image_new = str_replace("class=\"", "class=\"img-fluid ", $image);
$html = str_replace($image, $image_new, $html);
} else { // If no class defined, just add class attribute
$html = str_replace("<img ", "<img class=\"img-fluid\"", $html);
}
return $html;
}
add_filter( 'image_send_to_editor', 'add_bootstrap_class_to_images', 10, 3 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment