Skip to content

Instantly share code, notes, and snippets.

@davidrgreen
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrgreen/309022d02ea3edd15079 to your computer and use it in GitHub Desktop.
Save davidrgreen/309022d02ea3edd15079 to your computer and use it in GitHub Desktop.
Add a class to the P tag wrapping aligncenter and alignnone images in WordPress
<?php
/**
* Adds the img-parent class to the <p> tags WordPress automatically adds around aligncenter images.
* Adds <p> tags with the img-parent class to alignnone images
* I used https://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/ as a base
*/
function filter_ptags_on_images($content){
return preg_replace('/(<p>)?\s*(<a .*>)?\s*(<img.*class=".*(alignnone|aligncenter).*".*>)\s*(<\/a>)??\s*(<\/p>)??/iU', '<p class="img-parent">\2\3\5</p>', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment