0

I'm making a member-only site that requires users to be logged in to use the site.

The homepage is publicly viewable. On the homepage, I'd like to put in a function to redirect users to a page inside the site if they are logged in.

The code I tried

<?php if (is_user_logged_in() ) {
 wp_redirect ('dashboard' );
 exit;
 }
?>

Gives me a "headers already sent" error. The code is placed at the top of my php file.

What am I doing wrong?

3
  • Does it say where the headers ate sent from?
    – Bainternet
    Jul 24, 2011 at 16:27
  • /wp-includes/pluggable.php on line 934
    – javy
    Jul 24, 2011 at 16:38
  • try turning on wp_debug and see whats going on there
    – Bainternet
    Jul 24, 2011 at 17:57

2 Answers 2

1

I am not sure if you just simplified for example, but make sure you use full URL in wp_redirect() call.

Also rather than having it in template, I think it would be more appropriate to run this at template_redirect hook.

4
  • My solution is wp_redirect ( home_url("/dashboard") );, and I've put this code on line 1 of the template. Although I'm not familiar with hooks so you probably have a valid point. Why?
    – javy
    Jul 24, 2011 at 18:36
  • @javy template_redirect is semantically place in code like "WP knows what it needs to start loading and outputting, but you can change its mind". Start of template is "we are already loading this thing". If you don't want what's in template there is no reason to get that far in the process.
    – Rarst
    Jul 24, 2011 at 18:53
  • Makes sense, sounds like it saves some server utilization?
    – javy
    Jul 25, 2011 at 0:14
  • @javy I don't think difference in performance would be meaningful between too.
    – Rarst
    Jul 25, 2011 at 7:28
0
<?php if (is_user_logged_in() ) {
wp_redirect ( home_url("/dashboard") );
exit;
}
?>

Is what I've come up with, and works. Also, I think I also messed up by putting this below

<?php
/*Template Name: Home*/
?>

The new code is on line 1 and works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.