页面顶部显示的短代码输出

时间:2017-03-08 13:37:41

标签: php wordpress plugins shortcode

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

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

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

    return $datashortcode; 

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

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

在不知道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');

答案 1 :(得分:0)

这将解决您的问题,只需尝试

<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>
相关问题