3
class my_menu extends WP_Widget
{

function widget($args, $instance)
{

// Excerpt length filter
    $new_excerpt_length = create_function('$length', "return " . $excerpt_length . ";");

    if ( $instance["excerpt_length"] > 0 ) {
    add_filter('excerpt_length', $new_excerpt_length, 999);
    }
 //...
 }}

This filter works great if the post does not have an excerpt. How do I apply the same filter to a post that has an excerpt?

In other words, when the post has an actual excerpt, its not filtering it at all, the whole excerpt is displayed. However, when the post does not have an excerpt, the get_the_excerpt() call gets filtered so that it only returns the number of words specified by "excerpt_length"

1
  • I am puzzled by this. wp_trim_excerpt is applied to get_the_excerpt. The filter should work. I am wondering if the problem isn't somewhere else in your code. That you are doing this inside a widget raises a flag, but it really depends on the code you chopped out of your post. Please include that. – s_ha_dum Dec 13 '12 at 21:03
4

I posted an article about this a while ago:

function wp_trim_all_excerpt($text) {
// Creates an excerpt if needed; and shortens the manual excerpt as well
global $post;
   $raw_excerpt = $text;
   if ( '' == $text ) {
      $text = get_the_content('');
      $text = strip_shortcodes( $text );
      $text = apply_filters('the_content', $text);
      $text = str_replace(']]>', ']]>', $text);
   }

$text = strip_tags($text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); 

return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); 
}

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

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.