Skip to content

Instantly share code, notes, and snippets.

@txemaleon
Last active March 26, 2021 17:26
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save txemaleon/cf45cb3537d91d81b32914cc4b3f0a89 to your computer and use it in GitHub Desktop.
Save txemaleon/cf45cb3537d91d81b32914cc4b3f0a89 to your computer and use it in GitHub Desktop.
Allow HTML Tags in WordPress Excerpts
<?php
/**
* Allow HTML Tags in Wordpress Excerpt
*
* @link http://wordpress.stackexchange.com/questions/141125/allow-html-in-excerpt/141136
*/
if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) :
function wpse_custom_wp_trim_excerpt( $wpse_excerpt ) {
$raw_excerpt = $wpse_excerpt;
if ( '' == $wpse_excerpt ) {
$wpse_excerpt = get_the_content( '' );
$wpse_excerpt = strip_shortcodes( $wpse_excerpt );
$wpse_excerpt = apply_filters( 'the_content', $wpse_excerpt );
$wpse_excerpt = str_replace( ']]>', ']]&gt;', $wpse_excerpt );
//Set the excerpt word count and only break after sentence is complete.
$excerpt_word_count = 75;
$excerpt_length = apply_filters( 'excerpt_length', $excerpt_word_count );
$tokens = array();
$excerptOutput = '';
$count = 0;
// Divide the string into tokens; HTML tags, or words, followed by any whitespace
preg_match_all( '/(<[^>]+>|[^<>\s]+)\s*/u', $wpse_excerpt, $tokens );
foreach ( $tokens[0] as $token ) {
if ( $count >= $excerpt_length && preg_match( '/[\,\;\?\.\!]\s*$/uS', $token ) ) {
// Limit reached, continue until , ; ? . or ! occur at the end
$excerptOutput .= trim( $token );
break;
}
// Add words to complete sentence
$count++;
// Append what's left of the token
$excerptOutput .= $token;
}
$wpse_excerpt = trim( force_balance_tags( $excerptOutput ) );
$excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf( __( 'Read more about: %s &nbsp;&raquo;', 'wpse' ), get_the_title() ) . '</a>';
$excerpt_more = apply_filters( 'excerpt_more', ' ' . $excerpt_end );
$wpse_excerpt .= $excerpt_more; /* Add read more in new paragraph */
return $wpse_excerpt;
}
return apply_filters( 'wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt );
}
endif;
remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'get_the_excerpt', 'wpse_custom_wp_trim_excerpt' );
@webelious
Copy link

webelious commented May 7, 2018

Is there a way to have the 'Read More' show up after certain tags eg. <'pre'> <'code'> that would be perfect for formatted posts & the option above for word count = covers everything!

thanks matey!

@TopCheff
Copy link

TopCheff commented Jun 25, 2018

donde debo colocar este código? no consigo hacerlo funcionar en el extract(); del sitio web http://www.fim-isde2016.es

@annetscape
Copy link

Is there a way this could work for shortcodes? Using those in an excerpt?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment