Date:

Share:

Rediscovering WordPress by Josh Sherman

Related Articles

I recently received a request to update the navigation on the WordPress website. The way the request was worded made me think that the menu change should happen on one specific page, and not on the entire site.

This created an interesting problem, as the theme only seemed to support a single menu. It also didn’t help that the menu system, which I think might be baked into WordPress) didn’t support any kind of copy feature, without the need for third-party plugins.

None of this was going to stop me, so my next step was to learn a bit about the functions WordPress provides that would allow me to fiddle with the menu items before displaying said menu.

Fortunately, there is the filter_wp_nav_menu_objects() A function that does exactly what it says, it allows you to filter the objects of the navigation menu.

Since I only wanted it to apply to one page, I started by investigating the $post->page_name to limit the scope of when the logic will be applied.

From there, I looped through the menu items, and for my specific scenario, checked the URL and omitted the item I wanted to remove from the menu.

Putting it all together, it looks something like this, which would need to be added before where you call wp_nav_menu():

<?php
// Only apply to a particular page
if ($post->postname === 'some-page') {
    function filter_wp_nav_menu_objects($menu_items, $args) {
        // This is where we'll store the menu items we do want to display
        $next_menu_items = [];

        foreach ($menu_items as $menu_item) {
            // This is where you'll want to add any filtering logic. For me, I
            // set it up to skip over pages that match a particular URL
            if (strpos($menu_item->url, '/some-page') !== false) {
                continue;
            }

            $next_menu_items[] = $menu_item;
        }

        return $next_menu_items;
    }

    add_filter('wp_nav_menu_objects', 'filter_wp_nav_menu_objects', 10, 2);
}

wp_nav_menu($main_navbar_args);

Definitely a hack job, but there really isn’t much to it!

Unfortunately, after spending some time to understand all this, I discovered that the requirement is to update the menu on all pages, not just on one particular one.

Although I did more work than I should have, it’s always nice to learn something new. You never know when this will be something I need to figure out in the future.

good things? want more?

Weekly emails about technology, development and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Source

Popular Articles