Last active
May 24, 2022 10:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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