Remove shortcode from excerpt (have codes)

I have this line of code displaying the excerpt in the theme:

<p class="desc"><?php echo mb_strimwidth(strip_tags(get_the_content('')), 0, 220, '...'); ?></p>

How do I put this code in to strip out the shortcodes from the excerpt?

Read More
$text = preg_replace( '|[(.+?)](.+?[/\1])?|s', '', $text);

I’m just getting into cutting up PHP so I’m needing just a little bit of help with this one.

Thanks!

Related posts

Leave a Reply

3 comments

  1. DONT USE REGEX in this case!

    REGEX will remove your own notes from excerpts, for example:
    Hello, on May 27 [1995] , blabla

    so, better to use built-in function strip_shortcodes, which detects registered shortcodes and removes them:

    add_filter('the_excerpt','myRemoveFunc'); function myRemoveFunc(){
        return mb_strimwidth(strip_shortcodes(get_the_content()), 0, 220, '...');
    }
    
  2. Posting a solution worked for me based on @T.Todua solution:

    add_filter('get_the_excerpt','clean_excerpt');
    function clean_excerpt(){
        $excerpt = get_the_content();
        $excerpt = strip_tags($excerpt, '<a>'); //You can keep or remove all html tags
        $excerpt = preg_replace("~(?:[/?)[^/]]+/?]~s", '', $excerpt);
    
        return ($excerpt) ? mb_strimwidth($excerpt, 0, 420, '').new_excerpt_more() : '';
    }
    
    function new_excerpt_more($more = '') {
        global $post;
        return '...  <a href="'.get_permalink($post->ID).'" class="readmore">Read More »</a>';
    }
    

    I split it into two functions since I also use the “more” filter as follow:

    add_filter('excerpt_more', 'new_excerpt_more');