在 wordpress 的 echo 中输出简码

Output a shortcode inside an echo for wordpress

我正在尝试编写一个短代码,其中嵌套了另一个短代码。 [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>';
                }
?>

我认为我不应该尝试从 return 中调用 php。虽然我在某处读到我应该使用 "heredoc" 但我一直无法让它正常工作。

有什么想法吗?

谢谢

你的预感是对的。不要 return 中间带有 php 函数的字符串。 (可读性不是很好,上面的示例代码也行不通)

heredoc 无法解决此问题。虽然有用,但 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 way" 是将短代码嵌入到内容字符串中,然后 运行 通过 WordPress the_content filter 函数:

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>' );
     }