在字符串中执行WordPress短代码

时间:2013-12-18 13:27:54

标签: php wordpress eval shortcode

我有一个可能包含短代码的字符串,例如“这是带[anyshortcode1]的字符串,这是[anyshortcode2]”。我想显示字符串,其中包含运行放置位置的短代码。当我回显这个字符串时,它不会执行短代码,只是将它们打印出来,将它们留在括号中。我试图通过使用如下代码来解决这个问题:

$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]";
$pattern = get_shortcode_regex();
preg_match_all("/$pattern/",$string_with_shortcodes, $matches);
foreach ($matches[0] as $short) {
    $string_with_shortcodes = str_replace($short, 'do_shortcode("' . $short . '")', $string_with_shortcodes);
}
eval("\$string_with_shortcodes = \"$string_with_shortcodes\";");
echo $string_with_shortcodes;

这成功完成了字符串替换,但是使用eval函数导致错误:

  

解析错误:语法错误,意外T_STRING

我使用eval功能错了吗?或者是否有更简单的方法来完成从字符串中运行短代码?

2 个答案:

答案 0 :(得分:11)

要从字符串中执行shortcode,您必须使用do_shortcode()函数。

这是如何使用它:

$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]";
echo do_shortcode($string_with_shortcodes);

如果这不起作用,那么您的安装有问题。

另请注意,eval()不是代码中最好的命令..! :)

最后确保短代码仍然存在。有许多主题使用短代码来设置内容样式,然后,当用户安装另一个主题时,之前的短代码不再起作用,因为它们将被删除前一个主题。

答案 1 :(得分:2)

$string_with_shortcodes = str_replace($short, do_shortcode($short), $string_with_shortcodes);

我不确定你要用Eval做什么。