2

I have this custom function that get's the manually entered excerpt and trims it down but the problem I'm having is that it is trimming the characters down to 52 and instead I want it to return the first 52 Words like the normal excerpt.

Here's the custom that allows me to trim the manually entered excerpt

function themeTemplate_trim_excerpt( $content ) {
    return substr( strip_tags( $content ), 0, 52 );
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt');

This is the only way I've been able to cut the manually entered excerpt.

How do I make it trim it so it only shows the first 52 words?

Thanks for any feedback :)

4

The function you want is wp_trim_words(), example:

function themeTemplate_trim_excerpt( $content ) {
    $more = '...'; //where $more is optional
    return wp_trim_words($content, 52, $more);
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt');
2
  • 1
    Thank you for the reply, I will try this method as soon as I'm near a PC :) – Stephen Feb 26 '16 at 8:10
  • 1
    This doesn't seem to work for some reason and I don't know why - EDIT: My bad it does work I missed some a bracket xD Thanks for your help sir :) – Stephen Feb 26 '16 at 9:16
0

explode, array_filter, array_slice, and implode can pull the world by looking operating on the whitespace.

function themeTemplate_trim_excerpt( $content ) {

    // split the content by spaces, 
    // remove excess whitespace
    // pull the first 52 items, 
    // glue back together...

    return implode( ' ', array_slice( array_filter( explode( ' ', $content ) ), 0, 52 ) );
}

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'get_the_excerpt', 'template_trim_excerpt' );

Breakdown

// Convert the string to an array
$words = explode( ' ', $content );

// Remove any empty values
$words = array_filter($words);

// Grab the first 10 elements from the array
$first_x_words = array_slice($words, 0, 10);

// Convert the array to a string
$output = implode ( ' ', $first_x_words );

// Final value
echo $output;

Cons

  • Since these operations act on spaces, if there is HTML in your content, each attribute can be viewed as a word.
  • It's much easier to use wp_trim_words() - [ L2951 ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.