多个实例会破坏WordPress短代码

时间:2011-06-06 18:14:48

标签: php wordpress shortcode ob-get-contents

我写了一个基于id显示作者个人资料的短代码。例如,[user-profile id =“1”]将显示user-profile.php中为作者1定义的配置文件块。它可以工作(即使在同一页面上有多个实例)。

function user_profile( $atts, $content = null ) {
    extract(shortcode_atts(array('id' => ''), $atts));
    include 'user-profile.php';
}

...除了短代码输出在其他条目内容之前显示,无论它在代码中的位置如何。为了解决这个问题,我添加了这个修复:

function user_profile( $atts, $content = null ) {
    extract(shortcode_atts(array('id' => ''), $atts));
    function get_user_profile() { include 'user-profile.php'; }
    ob_start();
    get_user_profile();
    $output_string = ob_get_contents();
    ob_end_clean();
    return $output_string;
}

...它解决了定位问题但打破了短代码的多个实例。 [user-profile id =“1”]有效但是[user-profile id =“1”] [user-profile id =“2”]打破了它 - 页面在此时停止加载。

如何修改此选项以允许多个实例?

2 个答案:

答案 0 :(得分:0)

尝试这种方式:

[user-profile id="1"][/user-profile] [user-profile id="2"][/user-profile]

答案 1 :(得分:0)

问题解决了!我更新了user-profile.php代码中的代码,以便它全部是PHP并且没有使用任何回声。然后我将短代码功能更改为:

function user_profile( $atts, $content = null ) {
    global $post;
    extract(shortcode_atts(array('id' => ''), $atts));
    include 'user-profile.php';
    return $user_hcard;
}
相关问题