我有一个字符串可能包含短代码,例如"这是一个带[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函数错了吗?或者是否有更简单的方法来完成从字符串运行短代码?
为了shortcode
在字符串中执行from,您必须使用该do_shortcode()
函数.
这是如何使用它:
$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]"; echo do_shortcode($string_with_shortcodes);
如果这不起作用,那么您的安装有问题.
另请注意,这eval()
不是代码中最好的命令..!:)
最后确保短代码仍然存在.有许多主题使用短代码来设置内容的样式,然后,当用户安装另一个主题时,之前的短代码不再起作用,因为它们将与之前的主题一起被删除.