【发布时间】:2016-01-02 12:13:34
【问题描述】:
我为我的 wordpress 博客在我的 functions.php 中写了一个 preg_replace,让我的女朋友使用如下“短代码”:
[spoiler id="1" show="show me the list" hide="hide the list"]test1
test2<ul>test3
<li>list item 1</li>
<li>list item 2</li>
</ul>
[/spoiler]
我在functions.php中的preg_replace如下:
function BUFU_add_spoilers ($content)
{ global $post;
$pattern = "/\[spoiler id=\"(.*?)\" show=\"(.*?)\" hide=\"(.*?)\"\](.*?)\[\/spoiler\]/is";
$replacement ='<br><div align="right" style="margin: -58px 0 0 0"><a id="button_show_%SPOILID%_$1" onclick="document.getElementById(\'spoiler_%SPOILID%_$1\').style.display=\'block\'; document.getElementById(\'button_hide_%SPOILID%_$1\').style.display=\'\'; document.getElementById(\'button_show_%SPOILID%_$1\').style.display=\'none\';"><h5>[$2]</h5></a></div><div align="right"><a id="button_hide_%SPOILID%_$1" style="display: none" onclick="document.getElementById(\'spoiler_%SPOILID%_$1\').style.display=\'none\'; document.getElementById(\'button_hide_%SPOILID%_$1\').style.display=\'none\'; document.getElementById(\'button_show_%SPOILID%_$1\').style.display=\'\';"><h5>[$3]</h5></a></div><span id="spoiler_%SPOILID%_$1" style="display: none" class="spoilerBox">$4</span>';
$content = preg_replace($pattern, $replacement, $content);
$content = str_replace("%SPOILID%", $post->ID, $content);
return $content;
}
add_filter('the_content', 'BUFU_add_spoilers', 5);
如果“短代码”之间只有文本,一切都可以正常工作,但它不适用于上面的示例。扰流板将包括直到开头"<ul>"(或开头"<table>")的所有内容,所以test1 和test2 在扰流板中,test3 不在。
我只是不知道为什么。我在线测试了 preg_replace,它工作得很好。
我认为这与 wordpress 添加过滤器和内容以处理文本的方式有关,但我无法弄清楚......
结果只是一个空的... class="spoilerBox"></span> 后跟列表..
如果有人可以帮助我,将不胜感激! 这个问题我真的要疯了!
提前致谢,
不服
【问题讨论】:
-
您应该使用已经存在的功能来添加短代码 (codex.wordpress.org/Function_Reference/add_shortcode),而不是尝试重新创建它。
-
同意。我会调查的。现在谢谢你! =)
-
看看
Example with enclosed content: [baztag]content[/baztag]下的例子。您根本不需要正则表达式。 :) -
好的,我要感谢你让我更加关注编写自己的短代码!我按照它应该做的那样做,现在一切都很完美。 :)
标签: php wordpress filter preg-replace