我将编写一些示例代码,因此这是我遇到的问题的一个简短示例。
假设我在数据库中存储了以下文本:
[form]
  <ul>
    [each name="upgrades"]
      <li><input type="checkbox" [value name="upgrade_name" id="1"] />[value name="upgrade_name" id="2"]</li>
    [/each]
  </ul>
[/form]
如果对此文本运行do_shortcode,将解析each内容内的html标记内的短码,而不是each短码。但是,在each短码对其内容运行do_shortcode之前,不在each内容的html标记中的短码不会被解析,这应该是正确的行为。
换句话说,id为1的value短码被解析得太快(在form短码传递中),但是id为2的value短码直到each短码在其上运行do_shortcode时才被解析,因此它产生了正确的值。
我知道我可以将表单短码上的ignore_html标志设置为true,但这是不正确的,因为用户可能想要解析html标签以获得短码。
是否有针对此行为的解决方法?
Wordpress 4.6.1版
编辑:添加可重现代码
使用以下代码创建一个新插件:
<?php
/*
Plugin Name: Broken Shortcodes
Description: Shortcodes should not jump the gun in parsing html tag shortcodes of inner shortcode content.
*/
remove_filter('the_content', 'wpautop');
add_shortcode('form', function($atts, $content){
  echo "<textarea>This is the form's content:\n".$content.'</textarea>';
  return "<textarea>This is the rendered form shortcode:\n".do_shortcode($content).'</textarea>';
});
$bad_global_variable = 'first';
add_shortcode('value', function($atts, $content){
  global $bad_global_variable;
  return $bad_global_variable;
});
add_shortcode('each', function($atts, $content){
  global $bad_global_variable;
  $_content = '';
  foreach(array('second', 'third', 'fourth') as $v){
    $bad_global_variable = $v;
    $_content .= do_shortcode($content);
  }
  return $_content;
});
?>
创建包含此文本的页面:
[form]
  [each]
    <div [value]>[value]</div>
  [/each]
[/form]
输出不正确:
<div first>second</div>
<div first>third</div>
<div first>second</div>
<div first>fourth</div>
<div first>second</div>
<div first>third</div>
<div first>second</div>
发布于 2016-11-03 08:14:20
一种快速的解决方法是从html标签中解析出您自己的短码。
所以你的文本看起来会像这样:
[form]
  [each]
    <!-- Notice curly brackets -->
    <div {value}>[value]</div>
  [/each]
[/form]
然后,您的每个短代码可能如下所示:
add_shortcode('each', function($atts, $content){
  global $bad_global_variable;
  $content = preg_replace('/\{([^}]+)\}/', '[$1]', $content, -1);
  $_content = '';
  add_filter( 'wp_kses_allowed_html', 'parse_tags', 10, 2 );
  foreach(array('second', 'third', 'fourth') as $v){
    $bad_global_variable = $v;
    $_content .= do_shortcode($content);
  }
  remove_filter( 'wp_kses_allowed_html', 'parse_tags', 10, 2 );
  return $_content;
});
// This might be necessary depending on your use-case
function parse_tags($tags, $context){
  $tags['input']['value'] = true;
  return $tags;
}
但是,这不应该是一个解决看起来如此简单的事情的方法。我认为短码API需要一些TLC。
https://stackoverflow.com/questions/40390223
复制相似问题