How can I whitelist only specific shortcodes for processing in text widgets?

I know that I can use the following filters to enable processing of shortcodes in Text Widgets:

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

How can I only whitelist a few specific shortcodes for processing, but not just process every shortcode?

Related posts

2 comments

  1. add_filter( 'widget_text', 'wpse_137725_shortcode_whitelist' );
    
    /**
     * Apply only whitelisted shortcode to content.
     * 
     * @link http://wordpress.stackexchange.com/q/137725/1685
     * 
     * @param   string  $text
     * @return  string
     */ 
    function wpse_137725_shortcode_whitelist( $text ) {
        static $whitelist = array(
            'gallery',
            'form',
        );
    
        global $shortcode_tags;
    
        // Store original copy of registered tags.
        $_shortcode_tags = $shortcode_tags;
    
        // Remove any tags not in whitelist.
        foreach ( $shortcode_tags as $tag => $function ) {
            if ( ! in_array( $tag, $whitelist ) )
                unset( $shortcode_tags[ $tag ] );
        }
    
        // Apply shortcode.
        $text = shortcode_unautop( $text );
        $text = do_shortcode( $text );
    
        // Restore tags.
        $shortcode_tags = $_shortcode_tags;
    
        return $text;
    }
    
  2. Or little bit simplier.

    function do_shortcode_only_for($content, $tagnames) {
      $pattern = get_shortcode_regex($tagnames);
      $content = preg_replace_callback("/$pattern/", 'do_shortcode_tag', $content);
      return $content;
    }
    

    Taken from original do_shortcode function.

Comments are closed.