3

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?

2 Answers 2

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.