在wordpress

时间:2015-10-14 00:31:18

标签: 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 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”但我无法让它正常工作。

有没有?

由于

1 个答案:

答案 0 :(得分:2)

你的预感是对的。不要在其中间返回带有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方式”是将短代码嵌入到内容字符串中,并通过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>' );
     }
相关问题