在字符串中执行WordPress短代码

 国国国国涛 发布于 2023-02-09 14:23

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

1 个回答
  • 为了shortcode在字符串中执行from,您必须使用该do_shortcode()函数.

    这是如何使用它:

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

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

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

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

    2023-02-09 14:26 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有