我有一个短代码:[content\\u block]
如果该短代码存在于内容中,并且属性position=top,我想将其从内容中删除并在其他位置显示。例如,在侧栏中。
总而言之:
检测[内容块]是否存在,如果存在,检测是否有attibute position=top,如果有属性,则存储完整的短代码以将其显示在其他位置(例如在侧栏中)
谢谢
我有一个短代码:[content\\u block]
如果该短代码存在于内容中,并且属性position=top,我想将其从内容中删除并在其他位置显示。例如,在侧栏中。
总而言之:
检测[内容块]是否存在,如果存在,检测是否有attibute position=top,如果有属性,则存储完整的短代码以将其显示在其他位置(例如在侧栏中)
谢谢
您可以查看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;
add_filter( \'the_content\', \'wpse168789_shortcode_checker\' );
function wpse168789_shortcode_checker( $content ) {
// 1. Does the shortcode exist?
if( has_shortcode( $content, \'content_block\' ) ) {
// 2. Is it using position=\'top\'?
$regex = \'/\\[content_block[^\\]]*position=[\\\'"]?top[\\\'"]?[^\\]]*\\]/\';
if( preg_match( $regex, $content ) ) {
// 3. Filter the shortcode out of the_content
$content = preg_replace( $regex, \'\', $content );
}
}
return $content;
}
您可能需要处理正则表达式$regex
-- 我还没有测试过这个。至于在另一个位置显示短代码的内容--this question 可能会指引你。
has_shortcode()
preg_match()
preg_replace()
我试图通过这种方式添加一个短代码class MyPlugin { function __construct() { $this->make_shortcode(); } function ShowMsg($cls, $lst4) { $data = shortcode_atts(array(\'phn\' => \'\', \'msg\' => \'\'), $atts);