如何在div中包装wordpress短代码

时间:2012-02-24 16:10:22

标签: wordpress wordpress-theming

我创建了以下短代码功能来调用页面上特定位置的菜单

function servicesmenu() {
    return wp_nav_menu( array( 'theme_location' => 'services_nav', 'menu_id' => 'servicesmenu') );
}
add_shortcode('servicesMenu', 'servicesmenu');

以上代码工作正常。但是,当我试图将短代码包装在DIV中时,它没有包装,短代码生成的菜单在div id =“services_rightarea”之前出现

<div id="services_rightarea">
    <!-- other content here -->
    [servicesMenu]
</div>

任何解决方案

1 个答案:

答案 0 :(得分:0)

问题是默认情况下wp_nav_menu回声。您需要在变量中捕获此回显并将其返回。这可以通过output buffering

完成
function servicesmenu() {

    // Start output buffering
    ob_start(); 

    // The echo of this call is caught in the buffer
    wp_nav_menu( array('menu_id' => 'servicesmenu');

    // Capture contents of buffer in a variable
    $menu = ob_get_contents();

    // End buffering
    ob_end_clean();

    // Return your menu and bask in the warming glow of working code
    return $menu;
}
add_shortcode('servicesMenu', 'servicesmenu');

编辑:我刚刚注意到您还在使用theme_location属性。这会尝试将wp_nav_menu调用的结果插入servicesmenu菜单,该菜单已在register_nav_menu()注册。

取出theme_location参数,输出缓冲将按预期工作。