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

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;
}

Leave a Comment