我知道我可以使用以下过滤器来处理文本小部件中的短代码:
add_filter( \'widget_text\', \'shortcode_unautop\');
add_filter( \'widget_text\', \'do_shortcode\');
我怎样才能只列出几个特定的短代码进行处理,而不只是处理每个短代码?
最合适的回答,由SO网友:TheDeadMedic 整理而成
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;
}