在内容之前插入 Wordpress 简码

Wordpress shortcode is being inserted before content

我知道我们必须 return 短代码,但我正在尝试使用自定义模板,并且短代码被插入到所见即所得编辑器中的内容之前,而实际上它位于内容的末尾:

这是我的简码:

add_shortcode('test_temp', 'temp_handler');

function temp_handler($atts) { 
   ob_start();
   load_template(TEMPLATES_PATH . templates/test.php');
   return ob_get_contents();

}

这是 test.php 的样子:

 <div class="testDiv">Here is my test template</div>

还有什么办法可以不在内容前插入短码?

试试这个:

add_shortcode('test_temp', 'temp_handler');

function temp_handler($atts) { 
   ob_start();
   load_template(TEMPLATES_PATH . templates/test.php');
   $ret = ob_get_contents();
   ob_end_clean();
   return $ret;
}

您使用输出缓冲加载模板文件的想法是一个好主意,也是 Wordpress 短代码的常见做法。但是,我觉得您没有在您提供的代码中的任何地方结束输出缓冲,这让我觉得很奇怪,这让我相信您的输出缓冲设置不完美。

一般来说,Wordpress 会 运行 您的函数并用输出替换您的短代码标签。如果你的函数的输出显示在页面的其他地方(特别是如果它显示在它应该出现的区域上方)那么你的函数必须输出内容 因为 Wordpress 是 运行宁它(在你的情况下,它不能像预期的那样输出缓冲)。

注意:load_template 函数默认使用 require_once,这意味着您只能在页面上使用一次短代码。相反,我建议使用:load_template(TEMPLATES_PATH . templates/test.php', false);