【问题标题】:Executing WordPress Shortcodes in a String在字符串中执行 WordPress 简码
【发布时间】:2014-01-06 17:05:04
【问题描述】:

我有一个可能包含短代码的字符串,例如“这是一个带有 [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 函数错误?或者有没有更简单的方法来完成从字符串运行短代码?

【问题讨论】:

    标签: php wordpress eval shortcode


    【解决方案1】:

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

    这是如何使用它:

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

    如果这不起作用,则说明您的安装有问题。

    还要注意,eval() 不是您代码中最好的命令 .. ! :)

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

    【讨论】:

    • 哇,谢谢!我把这种方法弄得太复杂了。我误解了 do_shortcode 的工作原理。
    • 如果您找到了答案,请将其标记为答案。这样您就可以节省其他 StackOverflow 用户的时间;)啊...欢迎来到 WordPress 世界! :)
    • 此外,如果你有 $str = '<div>[shortcode]</div>' 这样的东西,如果你有 echo do_shortcode($str) 这样的魅力,它也可以工作
    【解决方案2】:
    $string_with_shortcodes = str_replace($short, do_shortcode($short), $string_with_shortcodes);
    

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

    【讨论】:

    • 他正试图让任何可以用eval 编写简码的人入侵他的网站。
    • 他是否知道他在做什么是另一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2012-07-26
    • 2011-07-27
    相关资源
    最近更新 更多