Skip to content

Instantly share code, notes, and snippets.

@Langmans
Last active July 17, 2018 12:44
Show Gist options
  • Save Langmans/5cf59e89ccc041548735aeadaa23e170 to your computer and use it in GitHub Desktop.
Save Langmans/5cf59e89ccc041548735aeadaa23e170 to your computer and use it in GitHub Desktop.
wordpress the_content with teaser (more tag), add to functions.php under wordpress theme
<?php
add_filter( 'the_content', function( $content ) {
$content = preg_replace_callback( "@(^.*)(<p>\s*(<span\s*id=\"more-\d+\">\s*</span>|<!--\s*more\s*-->)\s*</p>)@s", function ( $m ) {
return '<div class="article-teaser">' . $m[1] . '</div><!--/.article-teaser-->' . PHP_EOL . $m[2];
}, $content );
return $content;
});
<?php
add_filter( 'the_content', function( $content ) {
if ( preg_match( '@^(?<begin>.*)(?<more><!--\s?more(.*?)?-->|<span\s*id="more-\d+">\s*</span>)@s', $content, $m ) ) {
$more = $m['more'];
$ret = $m['begin'];
$tag_stack = [];
$offset = 0;
while ( preg_match( '@<(?<ending>/)?(?<tag>\w+)(?<attr>\s[^>]+)?>@', $m['begin'], $m2, PREG_OFFSET_CAPTURE, $offset ) ) {
$offset = $m2[0][1] + 1;
if ( $m2['ending'][0] ) {
array_pop( $tag_stack );
} else {
$tag = $m2[0][0];
// remove the id.
$tag = preg_replace( '@\s+id="[^"]+"@', '', $tag );
$tag = preg_replace( "@\s+id='[^']+'@", '', $tag );
$tag_stack[] = $tag;
}
}
$tag_stack2 = array_reverse( $tag_stack );
foreach ( $tag_stack2 as $tag ) {
$ret .= str_replace( '<', '</', $tag );
}
$ret = '<div class="article-teaser">' . PHP_EOL . $ret . PHP_EOL . '</div><!--/.article-teaser-->' . PHP_EOL . $more . PHP_EOL;
foreach ( $tag_stack as $tag ) {
$ret .= $tag;
}
$ret .= substr( $content, strlen( $m[0] ) );
$content = $ret;
}
return $content;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment