我写了一个wordpress插件。它是从API获取、解析和呈现数据的一组短代码。我现在正在写一个主题来支持这个插件。我注意到Wordpress将短代码内容从编辑器内容中分离出来,并分别呈现出来。下面是我的问题的一个例子:在管理面板中编辑页面或帖子:
<div class="row">
<div class="col-lg-12">
<p>HERE</p>
[PluginShortcode_1]
</div>
</div>假设PluginShortcode_1生成以下html:
<h1>This is the output of PluginShortcode_1</h1>
<p>Got Here!</p>我希望产出如下:
<div class="row">
<div class="col-lg-12">
<p>HERE</p>
<h1>This is the output of PluginShortcode_1</h1>
<p>Got Here!</p>
</div>
</div>而是将以下内容发送到浏览器:
<h1>This is the output of PluginShortcode_1</h1>
<p>Got Here!</p>
<div class="row">
<div class="col-lg-12">
<p>HERE</p>
</div>
</div>很明显,wordpress做了以下工作:
我已经看到了对短码()的引用,但是我的插件定义了许多短代码,并且不会在template.php中显式地知道哪些短代码或短代码在页面上,而不需要事先解析内容、选择所有的短代码并应用过滤器。
更新:
这些短代码函数位于一组类中,这些类处理所有呈现。大多数短代码内容分别存储在呈现内容的“视图”脚本中。
将以下列方式调用上面的示例:
shortcodes.ini -一个短代码及其相关功能的列表:
[shortcode_values]
PluginShortcode_1 = shortcodeOne
AnotherShortcode = anotherShortcodeShortcodes.php -用于短代码函数和调用的容器:
public function __construct() {
$ini_array = parse_ini_file(__DIR__. '/shortcodes.ini', true);
$this->codeLib = $ini_array['shortcode_values'];
foreach ($this->codeLib as $codeTag => $codeMethod) {
add_shortcode($codeTag, array(&$this, $codeMethod));
}
}
public function shortcodeOne() {
require_once(__DIR__ . 'views/shortcodeOneView.php');
}视图/configcodeOneView.php
<?php
?>
<h1>This is the output of PluginShortcode_1</h1>
<p>Got here!</p>其中,短代码函数实际上将负责获取数据,设置将公开给视图的变量。
更新使事情更加复杂,因为这个插件会发出API请求,所以我只在post内容实际包含一个短代码时才调用它。
在插件初始化脚本中,我有以下内容:
MyPlugin.php类:
public function __construct() {
. . .
add_filter('the_posts', array(&$this, 'isShortcodeRequest'));
. . .
}
public function isShortcodeRequest($posts) {
if (empty($posts)) { return $posts; }
foreach ($posts as $post) {
if (stripos($post->post_content, '[PluginShortcode') !== false) {
$shortcodes = new Shortcodes();
break;
}
}
return $posts;
}我担心的是,这个过滤器可能负责劫持输出。。.(?)
发布于 2015-05-21 17:39:26
嗯。在wp中,第199-200行中包含函数do_shortocode():
$pattern = get_shortcode_regex();
return preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $content );preg_replace正在对一个字符串进行操作。函数被调用。用所述内容对所述函数的输出进行插值。
所以,输出缓冲到救援!
public function shortcodeOne() {
ob_start();
require_once(__DIR__ . 'views/shortcodeOneView.php');
$buffer = ob_get_clean();
return $buffer;
}产生预期的输出!呼。(顺便提一句,我所有的短代码函数都调用了一个需要文件的呈现方法。把我从很多更新中救出来。谢谢@所有!
发布于 2015-05-21 17:00:59
问题是短代码回调,您是“回显”而不是返回这个,您应该用以下内容替换shortcodeOne():
public function shortcodeOne() {
return "<h1>This is the output of PluginShortcode_1</h1><p>Got here!</p>";
}在打印它之前,PluginShortcode_1解析它的输出,在您的例子中,当它解析PluginShortcode_1以获得它的内容时,您打印它,而WordPress作为回报具有null。
https://stackoverflow.com/questions/30379473
复制相似问题