Skip to content

Instantly share code, notes, and snippets.

@pirey
Last active May 24, 2022 10:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirey/fcd166931fba88d7ca8f4b4e91f294a7 to your computer and use it in GitHub Desktop.
Save pirey/fcd166931fba88d7ca8f4b4e91f294a7 to your computer and use it in GitHub Desktop.
Wordpress `the_content` filter, for adding class to img element in the page content
<?php
// other stuff ...
// register our filter to the wordpress action 'the_content',
// it will then be called when we call the_content() from anywhere in our template
add_filter( 'the_content', 'add_classlist_to_img' );
function add_classlist_to_img( $content ) {
// used to detect img tag element
$locateElement = '/\<img.*?\/\>/';
$content = preg_replace_callback($locateElement, function($imgElement) {
// add this class list to the element
$additionalClass = 'any additional classlist here';
// used to locate class attribute
$locateClass = '/class=(["\'])(.*?)\1/';
// the complete match
// see preg_replace_callback doc at php.net
$imgElement = $imgElement[0];
if (preg_match($locateClass, $imgElement, $class)) {
// the element already has class attribute, so we simply append our $additionalClass in it
$replacement = 'class=$1$2 '.$additionalClass.'$1';
} else {
// aim at the end of the element to insert class attribute
$locateClass = '/(\/\>)/';
// add class attribute to the element
$replacement = 'class="'.$additionalClass.'" $1';
}
return preg_replace($locateClass, $replacement, $imgElement);
}, $content);
// this will be content that will be printed on the page
return $content;
}
// other stuff ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment