php - Wordpress 短代码在错误的地方

标签 php wordpress plugins shortcode

我正在制作 wordpress 插件,我想使用短代码在帖子中插入一些相当大的代码。我得到了这个简单的代码来模拟我的问题

function shortcode_fn( $attributes ) {
    wanted();
    return "unwanted";
}
add_shortcode( 'simplenote', 'shortcode_fn');

function wanted(){
    echo "wanted";
}

并发布此内容
start
[simplenote]
end

这给出了这个结果:
wanted
start
unwanted
end

我希望它在开始和结束之间插入“想要的”文本。
我知道最简单的解决方案是在想要的()中返回“通缉”,但我已经拥有所有这些功能,而且它们非常庞大。没有从头开始编写所有内容的简单解决方案吗?

@edit:也许有什么方法可以将函数的所有 echo 存储在字符串中而不打印它?

最佳答案

一个简单的解决方法是使用 Output control职能:

function shortcode_fn( $attributes ) {
    ob_start(); // start a buffer
    wanted(); // everything is echoed into a buffer
    $wanted = ob_get_clean(); // get the buffer contents and clean it
    return $wanted;
}

关于php - Wordpress 短代码在错误的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23334359/

相关文章:

php - 将多个图像从 MySQL 数据库拉取到 Android 设备的最有效方法

php - 使用 json_encode 进行奇怪的 JSON 编码

html - 使用详细信息标签时如何将光标从 "text"更改为 "default"

wordpress - 如何创建付费插件/主题并安全地销售它们

mysql - 恢复 woocommerce 订单

plugins - Jenkins 中的 Gerrit-trigger 插件如何工作?

php - 我尝试使用 PHP 连接到 Azure 服务总线队列,但不断收到此错误

php - WordPress get_posts 函数中的多个数组键

jquery - 我有一个 Wordpress 驱动的网站,我的联系表单 7 插件在表单底部添加了大量空格,我不确定为什么

javascript - GWT 插件如何工作?