【问题标题】:Shortcode output shown at the top of the page页面顶部显示的简码输出
【发布时间】:2017-03-08 13:37:40
【问题描述】:

我知道这个问题与已发布的其他问题类似。我完全按照这些问题的答案中的建议进行操作,但仍然无法弄清楚为什么输出显示在页面顶部。

function foo_shortcode($atts, $content = null) { 

    $datashortcode = '<div>'.(function_exists('rtb_kk') ? rtb_kk() : '').'</div>';

    return $datashortcode; 

}
add_shortcode('showfoo', 'foo_shortcode');

有什么想法吗?

【问题讨论】:

    标签: php wordpress plugins shortcode


    【解决方案1】:

    在不知道rtb_kk() 函数如何工作的情况下,我只能假设它使用echo 来显示内容,而不是使用return。这就是导致该函数的输出出现在页面顶部的原因。

    要解决此问题,您可以使用ob_start()ob_get_clean() 捕获函数的输出:

    function foo_shortcode($atts, $content = null) { 
        if (function_exists('rtb_kk')) {
            // Start output buffering
            ob_start();
            // Run the function
            rtb_kk();
            // Capture buffer as a string
            $output = ob_get_clean();
        } else {
            // Function doesn't exist so we return an empty string
            $output = ''; 
        }
    
        return '<div>' . $output . '</div>'; 
    }
    add_shortcode('showfoo', 'foo_shortcode');
    

    替代方法

    如果您能够使用bcn_display() 而不是您正在使用的rtb_kk() 方法,则无需依赖ob_get_clean()

    function foo_shortcode($atts, $content = null) { 
        if (function_exists('bcn_display')) {
            // Return the output as a string so we can control when it's displayed
            $output = bcn_display( true );
        } else {
            // Function doesn't exist so we return an empty string
            $output = ''; 
        }
    
        return '<div>' . $output . '</div>'; 
    }
    add_shortcode('showfoo', 'foo_shortcode');
    

    【讨论】:

    • 感谢您的回答,它运行良好,但显示双输出。一个包含在&lt;div&gt; 中,另一个不包含在 div 中。知道为什么要使用这种有线输出吗?
    • rtb_kk() 来自哪里?是插件吗?
    • @Arstik 我已更新我的答案以使用ob_get_clean() 而不是ob_get_flush()。这应该返回输出而不将其打印到屏幕上。更多详细信息,请访问this answer
    • rtb_kk() 实际上是 bcn_display() 来自:wordpress.org/plugins/breadcrumb-navxt/installation
    • 更新的问题就像魅力一样。谢谢你的帮助:)
    【解决方案2】:

    这会解决你的问题,试试吧

    <script type="text/javascript">
    function foo_shortcode($atts, $content = null) {
        if(function_exists('rtb_kk')){
            $rtb_kk = rtb_kk();
        }else{
            $rtb_kk = '';
        }
        $datashortcode = "<div>$rtb_kk</div>";
        return $datashortcode;
    }
    add_shortcode('showfoo', 'foo_shortcode');
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多