Last active
May 10, 2017 18:05
-
-
Save rodriigomedeiros/d2dea1138886fb49be361c8f522b7e76 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Remove a imagem da tag <p> e adiciona em um nova tag com as classes has-image e no-padding. Adiciona a tag img a class img-responsive. | |
* Pode ser prevenida através da adição de um atributo ou espaço em branco para <p>, por exemplo, <p class="lorem">ou mesmo <p > | |
*/ | |
function updateTagPInContent( $content ) { | |
return preg_replace_callback( '/<p>((?:.(?!p>))*?)(<a[^>]*>)?\s*(<img[^>]+>)(<\/a>)?(.*?)<\/p>/is', | |
function ( $matches ) { | |
/* | |
Groups Regex Description | |
<p> starting <p> tag | |
1 ((?:.(?!p>))*?) match 0 or more of anything not followed by p> | |
.(?!p>) anything that's not followed by p> | |
?: non-capturing group. | |
*? match the ". modified by p> condition" expression non-greedily | |
2 (<a[^>]*>)? starting <a> tag (optional) | |
\s* white space (optional) | |
3 (<img[^>]+>) <img> tag | |
\s* white space (optional) | |
4 (<\/a>)? ending </a> tag (optional) | |
5 (.*?)<\/p> everything up to the final </p> | |
i modifier case insensitive | |
s modifier allows . to match multiple lines (important for 1st and 5th group) | |
*/ | |
// image and (optional) link: <a ...><img ...></a> | |
$image = $matches[2] | |
. preg_replace( "/<img(.*?)class=\"(.*?)\"(.*?)>/is", | |
'<img$1class="$2 img-responsive"$3>', | |
$matches[3] ) | |
. $matches[4]; | |
// content before and after image. wrap in <p> unless it's empty | |
$content = trim( $matches[1] . $matches[5] ); | |
if ( $content ) { | |
$content = '<p>' . $content . '</p>'; | |
} | |
return '<p class="has-image no-padding">' . $image . '</p>' . $content; | |
}, $content ); | |
} | |
add_filter( 'the_content', 'updateTagPInContent' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment