Skip to content
Advertisement

WordPress/PHP get all navigation links

I am working on a small plugin and am wondering how can I get all links in primary navigation? Wondering if it’s possible without knowing the name or slug of the menu in a particular theme.

Below I was trying to get all menu links and return them in a script tag but it didn’t work out too well. It ended up returning a bunch of metadata and on one site it broke the site completely.

For now, the script tag is only for testing purposes, where I am going to use the navigation links in an unordered list later on.

function get_nav_menu_items_by_location( $location, $args = [] ) {
    ?>
<script type = "application/ld+json" alt="hejtest" >
<?
    // Get all locations
    $locations = get_nav_menu_locations();
 
    // Get object id by location
    $object = wp_get_nav_menu_object( $locations[$location] );
 
    // Get menu items by menu name
    $menu_items = wp_get_nav_menu_items( $object->name, $args );
    
   // Return menu post objects
    return $menu_items;
?>
</script>
<?
    }
    add_action('wp_head', 'get_nav_menu_items_by_location');
    ```

Advertisement

Answer

You can’t “return” data from PHP to JS. The return keyword tells PHP that you’ve finished the get_nav_menu_items_by_location function, and to give that value to the calling PHP code.

To run JavaScript, you need to output some code that the browser will then execute when it receives the HTML.

If you want to output some data in a way that’s easy for JS to read, you can abuse the fact that JSON format is valid JS code, and write echo json_encode($menu_items);. You also need to output code to assign it to a variable, or pass it to a function.

If the function you’re writing is expected to return some HTML, you don’t want to use echo, and also don’t want to use ?>. Instead, you want to build up a PHP string containing the HTML and return that.

So you might end up with this:

function get_nav_menu_items_by_location( $location, $args = [] ) {
    $html = '<script type="application/ld+json" alt="hejtest">';

    // Get all locations
    $locations = get_nav_menu_locations();
 
    // Get object id by location
    $object = wp_get_nav_menu_object( $locations[$location] );
 
    // Get menu items by menu name
    $menu_items = wp_get_nav_menu_items( $object->name, $args );
    
    $html .= "var my_menu_items = " . json_encode($menu_items) . ";";

    $html .= "</script>";

    return $html;
}
add_action('wp_head', 'get_nav_menu_items_by_location');
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement