Awais Imran
Awais Imran

Reputation: 1344

Wordpress how to get the output before the header in the templates using header.php

Requirement: I have a following script to locked the Wordpress pages. It is working fine when I applied on a specific template. So instead of adding the script on 17 different templates, I put it on the header.php file using !is_front_page() statement so script should work on all pages except the homepage.

Problem: The script only work if I put it on the very top of the page at line number 1 without any space, otherwise it throwing error (Warning: Cannot modify header information - headers).

Error Reason in my case: As I mentioned earlier, that I put the following script in header.php file. So error is showing up because of this line <?php get_header(); ?> which is in the templates file (and following code must be before of the <php get_header(); ?>. So my question is, is there any turnaround that we can do with the following script or I need to put the script on all templates manually on the first line?

 <?php
      if(!is_user_logged_in())
      $redirect = home_url() . '/wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] );
      wp_redirect( $redirect );
 ?>

Upvotes: 0

Views: 1427

Answers (1)

Simon Pollard
Simon Pollard

Reputation: 2588

You could try this in your functions.php - hooking your code into a WordPress hook so it fires before the header is called etc... This means it gets called on every page as well.

function password_protected() {
    if ( !is_user_logged_in() ) {
        $redirect = home_url() . '/wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] );
        wp_redirect( $redirect );
    }
}
add_action('init', 'password_protected');

Updated thanks to @rnevius

Upvotes: 1

Related Questions