Php 在wordpress的echo中输出一个短代码
我正在尝试编写一个短代码,其中嵌套了另一个短代码。[map id=“1”]短代码是从不同的插件生成的,但我希望在执行此短代码时显示地图 我不认为这是最好的方法,但我仍然是新的php编码Php 在wordpress的echo中输出一个短代码,php,wordpress,function,return,shortcode,Php,Wordpress,Function,Return,Shortcode,我正在尝试编写一个短代码,其中嵌套了另一个短代码。[map id=“1”]短代码是从不同的插件生成的,但我希望在执行此短代码时显示地图 我不认为这是最好的方法,但我仍然是新的php编码 <?php add_shortcode( 'single-location-info', 'single_location_info_shortcode' ); function single_location_info_shortcode(){ return '<div cl
<?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函数中间返回一个带有PHP函数的字符串。(可读性不强,上面的示例代码无法使用) heredoc不能解决这个问题。虽然很有用,但heredocs实际上只是在PHP中构建字符串的另一种方式 有一些潜在的解决方案 “PHP”解决方案是使用输出缓冲区:
以下是您修改后的代码,可以满足您的要求:
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>';
}
功能单位置信息短码($atts){
//首先,启动输出缓冲区
ob_start();
//然后,运行短代码
do_短代码('[map id=“1”]');
//接下来,将短代码的内容放入变量中
$map=ob_get_clean();
//最后,将map短代码的内容放入这个短代码中
返回'
标题
副本
标题2
副本2
“.$map。”
';
}
替代方法
执行此操作的“WordPress方法”是将短代码嵌入到内容字符串中,并通过WordPress函数运行它:
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>' );
}
功能单位置信息短码($atts){
//通过“the_content”过滤器,短代码实际上由WordPress解析
返回apply_筛选器('the_content','
标题
副本
标题2
副本2
[map id=“1”]
' );
}