Blogs

customexcerpt

  WordPress: Limit posts Excerpt by number of paragraphs

Publicidad Google

To limit WordPress posts Excerpt by number of paragraphs add to the file function.php of your theme:

if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) { 
    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {
        global $post;
        $raw_excerpt = $wpse_excerpt;
        if ( '' == $wpse_excerpt ) {

            // Define here how many paragraphs to show
            $nb_parag = 3;

            $count_par = 0;
            $count_lines = 0;

            $wpse_excerpt = get_the_content('');
            $wpse_excerpt = strip_shortcodes( $wpse_excerpt );
            $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);
            $wpse_excerpt = str_replace(']]>', ']]>', $wpse_excerpt);
            $wpse_excerpt = strip_tags($wpse_excerpt, '<p>'); 

            $lines = preg_split('/\n|\r\n?/', $wpse_excerpt);

            foreach ($lines as $line){
                if (trim($line)){
                    if ($count_par == $nb_parag - 1) {
                        if ($count_lines < count( $lines ) ) {
                            // Add ... if content is bigger than excerpt
                            $excerptOutput .= "<p>".$line." ...</p>";
                        }
                        else {
                            $excerptOutput .= "<p>".$line."</p>";
                        }
                        break;
                    }
                    $excerptOutput .= "<p>".$line."</p>";
                    $count_par++;
                }
                $count_lines++;
            }
            $wpse_excerpt = trim(force_balance_tags($excerptOutput));
            return $wpse_excerpt;   
        }
        return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);
    }
}

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