Skip to content

Instantly share code, notes, and snippets.

@mikeoberdick
Last active July 28, 2022 15:23
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 mikeoberdick/c5e6d1d975575ccad2495b4671afa949 to your computer and use it in GitHub Desktop.
Save mikeoberdick/c5e6d1d975575ccad2495b4671afa949 to your computer and use it in GitHub Desktop.
Create a custom excerpt from ACF field
//Custom excerpts for ACF fields
function wp_trim_excerpt_modified($text, $content_length = 55, $remove_breaks = false) {
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = excerpt_remove_blocks( $text );
$text = apply_filters( 'the_content', $text );
$text = str_replace(']]>', ']]>', $text);
$num_words = $content_length;
$original_text = $text;
$text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text );
// Here is our modification
// Allow <p> and <strong>
$text = strip_tags($text, '<p>,<strong>');
if ( $remove_breaks )
$text = preg_replace('/[\r\n\t ]+/', ' ', $text);
$text = trim( $text );
if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
preg_match_all( '/./u', $text, $words_array );
$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
$sep = '';
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
$sep = ' ';
}
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
} else {
$text = implode( $sep, $words_array );
}
}
return $text;
}
//Heres' how to use it:
<?php $trimmed_text = wp_trim_excerpt_modified( get_field('the_content'), 40 );
$last_space = strrpos( $trimmed_text, ' ' );
$modified_trimmed_text = substr( $trimmed_text, 0, $last_space );
echo '<p class="excerpt mb-0">' . $modified_trimmed_text . '...</p>'; ?>
</div><!-- .the-excerpt -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment