add_filter on "the_excerpt" only works when post does not have excerpt

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

Topic excerpt filters Wordpress

Category Web


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');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.