Stop strip_shortcodes() stripping content inside shortcodes

I have this shortcode:

add_shortcode('refer', function($atts, $text)
{
    $defaults = ['link' => '', 'nofollow' => true];
    $atts     = shortcode_atts($defaults, $atts, 'refer' );
    $nofollow = $atts['nofollow'] ? 'rel="nofollow"' : 'external';

    return sprintf('<a href="https://wordpress.stackexchange.com/questions/228830/%s" %s>%s</a>', esc_url($atts['link']), $nofollow, $text);
});

with demo post content:

[refer link=”http://www.lipsum.com”]Lorem Ipsum[/refer] is simply dummy text of the printing and typesetting industry. [refer link=”http://www.lipsum.com”]Lorem Ipsum[/refer] has been the standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing [refer link=”http://www.lipsum.com”]Lorem Ipsum[/refer] passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

The loop to echo out the excerpt:

while ( have_posts() ) : the_post();
    the_excerpt();
endwhile;

The result:

is simply dummy text of the printing and typesetting industry. has been the standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. […]

Notice that all Lorem Ipsum words were stripped from the excerpt.

After looking over the_excerpt() and other related functions, I found out the problem was caused by strip_shortcodes() inside wp_trim_excerpt function.

But because of strip_shortcodes() has no filters, how can I change its behavior?

1 Answer
1

Try the filters in your functions.php:

add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');

Props: @bainternet (Source)

Or, use your own filter on get_the_excerpt. Put this in your theme’s functions.php:

function custom_excerpt($text="") {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        $text = get_the_content('');
                // $text = strip_shortcodes( $text );
        $text = do_shortcode( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $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', 'custom_excerpt'  );

This will allow shortcodes in the_excerpt().

Props to @keesiemeijer (source)

Leave a Comment