您可以查看WordPress用于解析短代码的代码,了解如何做到这一点。有几个有用的核心函数可以简化事情。
// our callback function to check for the shortcode.
// this is where you\'d put code to set a flag for rendering the shortcode elsewhere
// the complete tag is in $tag[0], which can be passed to do_shortcode later
function wpd_check_shortcode( $tag ){
if( \'content_block\' == $tag[2] ){
// convert string of attributes to array of key=>val pairs
$attributes = shortcode_parse_atts( $tag[3] );
if( array_key_exists( \'position\', $attributes )
&& \'top\' == $attributes[\'position\'] ){
// move shortcode to sidebar here
// return empty to strip shortcode
return \'\';
}
}
// return any non-matching shortcodes
return $tag[0];
}
// source text with shortcode
$text = \'lorem ipsum [content_block]\';
// this generates a regex pattern for all registered shortcodes
$pattern = get_shortcode_regex();
// process all shortcodes through our callback function
$text = preg_replace_callback( "/$pattern/s", \'wpd_check_shortcode\', $text );
// modified $text with shortcode removed
echo $text;