Comments On Code

Posts on WordPress

Jan 04, 2018

Private means Private

Working with a longterm client today, I rediscovered an odd behavior in WordPress. Her business is seasonal, with varying locations and itinerary, so she needs to be able to turn pages on and off, adding or removing from the menu as necessary. She has been taught to set unneeded pages to "private." After doing so, that page was still visible in the menu and accessible even to logged out users!

It is easy enough for me to simply remove the page, and then later add it back in via the custom menu tools. However, this is a problem I wanted to solve in a way that didn't require extra steps every time a menu item needed to be made invisible. I started with looking for a plugin. Usually, behavior like this is a solved problem, and I expected to quickly find something and implement it. The only solutions I found either didn't work, or required accessing menu items directly to control their visibility. This client needed to be able to continue to perform the single action she was used to, without having to remember additional steps (who does?).

Google turned up some CSS solutions, which is less than ideal. The data is still being received, it just ends up being hidden. While the situation here is not particularly sensitive, there is no need to send data that isn't intended to be received.

Finally, I discovered a way to programmatically remove private items from the menu itself, following a stack overflow thread.

The reason (I think) that private or non-published items show up in menus is that the menu items are themselves posts and have their own post status. That means that in a situation where a page is marked private, the menu item for that page can still be set to publish, and is displayed. I wrote a filter callback for the wp nav menu objects hook which looks at the post_status for the object that the menu item stands for, and removes it from the menu if that object is private. - user jjaderberg

I edited the code a bit to suit my use case, and turned it into a simple plugin to avoid editing my client's theme files directly.

  function nmo_hide_pages_from_menu ($items, $args) {

foreach ($items as $item => $list) {

if (get_post_status ($list->object_id) == ('private') || get_post_status ($list->object_id) == ('draft')) {

unset ($items[$item]);

}

}

return $items;

}

add_filter ('wp_nav_menu_objects', 'nmo_hide_pages_from_menu', 10, 2);

The plugin is available on my business site http://nmomedia.com/services/web-services/products/wordpress-plugins/hide-menu-items/. Future development goals are to add plugin options, like whether to show items in menus to logged in users, or certain user roles.