I need to style the element that goes around images embedded in a post that don’t have captions, but as far as I can tell there is no way to automatically add a class to it or target <a>
s with an <img>
inside only without using jQuery or something.
This is how they come out by default:
<a href="sample.jpg"><img class="alignnone size-full wp-image-20" src="sample.jpg" alt="Sample Image" width="1280" height="914"></a>
Is there a simple wordpress PHP method with which I can just set a simple “.img” class on all those elements by default?
Confused how this is not standard functionality in WordPress, lots of people complaining about it but no actual solutions as far as I can see.
To clarify, this should work on existing images in posts, not just on future posts I make!
If you have the ability to edit your functions.php file, then add this code. It is tested and proven:
Brief Explanation and Example
After retrieving the post from the data base, this will put all of the specified classes into the anchor tag whenever there is an anchor tag with only an image tag inside of it.
It works with many image tags in one post, as well as a variety of other weird possibilities. For instance, something like this
will become
Code (for functions.php)
Other Notes
(?![^>]*class)
is a negative lookahead so that the first regex replace rule only affects<a href...><img></a>
, not<a class... href...><img></a>
. (Read more on lookarounds.)[^>]*
is better than.*
.[^>]*
means zero or more characters that are not a>
. Without[^>]*
, I think there could be problems if there are multiple>
characters on one line or in other weird situations.'<a1 class="' . $classes . '"><img3></a>'
refers to the stuff inside corresponding parenthetical block in the corresponding pattern. In other words,1
means “put the stuff that matches what’s inside the first set of parentheses”.add_filter('the_content', 'add_classes_to_linked_images', 10, 1);
, the first parameter is the filter for getting the content of a post from the database, the second parameter is the name of the function we want to use, the third parameter is the priority of the filter (higher numbers are executed later), and the fourth parameter is the number of arguments for the filter.My friend had the same problem when trying to add prettyPhoto rel’s on his image, there are 1000’s of links for this.
Try adding this into your functions.php file within your theme. Please also remember NEVER to edit the core files, no matter what anyone says.
This was originally for adding
rel="prettyPhoto"
within the<a>
tags, try it now and remember to changeclass="newClassHere"
to your class.Just put this in your functions.php