【问题标题】:Output a shortcode inside an echo for wordpress在 wordpress 的回显中输出简码
【发布时间】:2015-10-14 00:31:18
【问题描述】:

我正在尝试编写一个短代码,其中嵌套了另一个短代码。 [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 wordpress function return shortcode


    【解决方案1】:

    你的预感是对的。不要返回中间带有 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>' );
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多