Front-End & Daily

[WordPress] How to hide private pages in wp_nav_menu

[WordPress] How to hide private pages in wp_nav_menu

Introducing a filter hook to hide private pages in menus created with wp_nav_menu() in WordPress.

What I want to do

When a static page is set to private

Private static page

This part of the menu also becomes "private", but

WordPress Menu Private

It still appears in the actual menu.(Even when logged out of WordPress)

Menu

Therefore,

Add the following code to functions.php.

//メニューから非公開のページは削除
function hide_private_pages_from_menu ($items, $args) {
	foreach ($items as $ix => $obj) {
		if (!is_user_logged_in () && 'private' == get_post_status ($obj->object_id)) {
			unset ($items[$ix]);
		}
	}
	return $items;
}
add_filter ('wp_nav_menu_objects', 'hide_private_pages_from_menu', 10, 2);

Then, it disappeared from the menu.(Please check while logged out of WordPress)

Disappeared from menu

(Reference) navigation - Exclude Private, Draft pages from Primary Nav when using custom menu - WordPress Development Stack Exchange

Comments

After reviewing the content, personal information will be omitted before publication.

Enter your name and email address

Please enter if you would like a reply via email.

The personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and then "Send".

If this was helpful, we appreciate your support!
Your support will be used for childcare.

OFUSEで応援を送る


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, "Ken" earns from qualifying purchases.

Share

Twitterでシェア Facebookでシェア LINEでシェア はてなブックマークでシェア