How to Hide Navigation Menu, Sidebar or Comment Section of Password Protected Content

In this article, we will show you how to hide certain areas of your website such as the navigation menu, sidebar, and comment section until the password is entered.

Single Page Protection

First of all, navigate to the template used for the protected content. Locate the function where a navigation menu, a sidebar, or a comment area is called.

  • wp_nav_menu() refers to displaying a navigation menu
  • get_sidebar() refers to loading sidebar template
  • comments_template() refers to loading the comment area

Wrap this call with the conditional statement used to determine content is password protected or not: post_password_required()

Let’s say you want to show the navigation menu in a post only if it’s not protected or a valid password cookie exists. Your custom code will be something like below:

<?php 

// Hide navigation menu
if ( ! post_password_required() ) {
     wp_nav_menu(array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ));
}

// Hide comment section
if ( ! post_password_required()) {
    comments_template();
}

// Hide sidebar
if ( ! post_password_required()) {
    get_sidebar();
}

Please note that your changes will be disappeared after the theme update. It’s recommended to create a child theme and make the changes with the child version.

Parts of content protection

This is how you can hide your comment while protecting certain content sections.

Step 1: Open your child theme comments.php file. Then wrap your comment sections with our PPWP shortcode.

<?php
ob_start();
/**
 * The template for displaying comments.
 *
 * This is the template that displays the area of the page that contains both the current comments
 * and the comment form.
 *
 * @package HelloElementor
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
// Comment Reply Script.
if ( comments_open() && get_option( 'thread_comments' ) ) {
	wp_enqueue_script( 'comment-reply' );
}
?>
<section id="comments" class="comments-area">
//Comment area here
</section><!-- .comments-area -->
<?php
$content = ob_get_clean();
echo do_shortcode( '[ppwp pwd_label="subscribers" hidden_form_text=""]' . $content . '[/ppwp]' );

Step 2: Put the following codes on your (child) theme’s functions.php

add_filter('ppw_content_shortcode_source', 'ppw_content_shortcode_source', 12, 2);
function ppw_content_shortcode_source( $content, $post ) {
	if ( 'post' === $post->post_type ) {
		return '[ppwp pwd_label="subscribers"]';
	}
	return $content;
}

Change the shortcode highlighted in red on line 4, i.e. [ppwp pwd_label="subscribers"], according to the one you use on step 1. In fact, the shortcode should match exactly with the one used on step 1 including but not limited to the passwords and other attributes, e.g. hidden_form_text.

Check out how to use our ppwp shortcode.

Lasted updated on July 10, 2020