How to Add a Private Page to WordPress Navigation Menu

Home » Snippets » How to Add a Private Page to WordPress Navigation Menu
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you have certain pages on your WordPress site that you’d like to keep hidden from the public eye? Maybe you have a page for your team members or a page for testing purposes that you only want accessible to certain users. While WordPress makes it easy to create private pages, adding them to your site’s navigation menu can be a bit trickier. In this article, I’ll show you how to add a private page to your navigation menu so that only authorized users can access it.

					function wpturbo_add_private_page_to_nav( $items, $args ) {
    // Check if current menu is the "Main Navigation" menu
    if ( 'main-navigation' === $args->menu_slug ) {
        // Get the private page by ID
        $private_page = get_post(123);
        // Check if private page exists and is published
        if ( $private_page && 'publish' === $private_page->post_status ) {
            // Add private page to the beginning of the menu
            $items = '<li class="menu-item"><a href="' . get_permalink( $private_page->ID ) . '">' . $private_page->post_title . '</a></li>' . $items;
        }
    }
    return $items;
}
add_filter( 'wp_nav_menu_items', 'wpturbo_add_private_page_to_nav', 10, 2 );
				

This code snippet explains how to add a private page to the navigation menu on your WordPress website. Normally, when you create a private page in WordPress, it is not visible in the front-end navigation menu. This code snippet will add a private page to a specific navigation menu by ID.

The function wpturbo_add_private_page_to_nav() uses the wp_nav_menu_items filter hook in WordPress to add the private page to the navigation menu. In this case, we are looking for the "Main Navigation" menu.

If the current menu is the "Main Navigation" menu, we get the private page using its ID and check if it exists and is published. If the page exists and is published, then we add it to the beginning of the menu with the title of the page as the anchor text.

The get_permalink() function gets the URL of the private page, and we use post_title to get the title of the page. We then concatenate the HTML markup to display the link and add the private page to the beginning of the $items list.

Finally, we return the updated $items list to WordPress, and the private page will now appear as the first item in the navigation menu.

This code snippet is useful if you have a private page that you want to share with specific users, and you want them to be able to access it easily through the navigation menu. It also eliminates the need to create a separate navigation menu just for the private page.

Register an account to save your snippets or go Pro to get more features.