Custom excerpt shortcode with variable length

function sk_excerpt_func( $atts ) {
	$atts = shortcode_atts( array(
        'length' => 100,
		'end' => "…"
    ), $atts );
	
	$excerpt = get_the_excerpt();
	$maxchar = $atts['length'];
	$end = $atts['end'];
	
	if (strlen($excerpt) > $maxchar || $excerpt == '') {
        $words = preg_split('/\s/', $excerpt);      
        $output = '';
        $i      = 0;
        while (1) {
            $length = strlen($output)+strlen($words[$i]);
            if ($length > $maxchar) {
                break;
            } 
            else {
                $output .= " " . $words[$i];
                ++$i;
            }
        }
        $output .= $end;
    } 
    else {
        $output = $excerpt;
    }
	
	return $output;
}
add_shortcode( 'sk_excerpt', 'sk_excerpt_func' );

Newsletter Updates

Enter your email address below to subscribe to my newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *