我正试图编写一个短代码,其中嵌套了另一个短代码。[map id="1"]短代码是从不同的插件生成的,但我想有地图显示,当我执行这个短代码。
我不认为这是最好的方式去做这个,但我仍然是新的php编码。
<?php
add_shortcode( 'single-location-info', 'single_location_info_shortcode' );
function single_location_info_shortcode(){
return '<div class="single-location-info">
<div class="one-half first">
<h3>Header</h3>
<p>Copy..............</p>
</div>
<div class="one-half">
<h3>Header 2</h3>
<p>Copy 2............</p>
<?php do_shortcode( '[map id="1"]' ); ?>
</div>
</div>';
}
?>
我不认为我应该尝试从返回....内调用php我想我在某个地方读到我应该使用"heredoc",但我一直无法让它正确工作。
有什么想法吗?
谢谢
你的预感是对的。不要返回中间有php函数的字符串。(不是很好读,上面的示例代码不起作用)
一个文档不能解决这个问题。虽然有用,但heredocs实际上只是在PHP中构建字符串的另一种方式。
有几个可能的解决方案。
"PHP"的解决方案是使用输出缓冲区: ob_start
ob_get_clean
这是你修改后的代码,将做你所要求的:
function single_location_info_shortcode( $atts ){
// First, start the output buffer
ob_start();
// Then, run the shortcode
do_shortcode( '[map id="1"]' );
// Next, get the contents of the shortcode into a variable
$map = ob_get_clean();
// Lastly, put the contents of the map shortcode into this shortcode
return '<div class="single-location-info">
<div class="one-half first">
<h3>Header</h3>
<p>Copy..............</p>
</div>
<div class="one-half">
<h3>Header 2</h3>
<p>Copy 2............</p>
' . $map . '
</div>
</div>';
}
替代方法
"WordPress的方式"是将短代码嵌入到内容字符串中,并通过WordPress的the_content过滤函数运行它:
function single_location_info_shortcode( $atts ) {
// By passing through the 'the_content' filter, the shortcode is actually parsed by WordPress
return apply_filters( 'the_content' , '<div class="single-location-info">
<div class="one-half first">
<h3>Header</h3>
<p>Copy..............</p>
</div>
<div class="one-half">
<h3>Header 2</h3>
<p>Copy 2............</p>
[map id="1"]
</div>
</div>' );
}