I have a page which a require users to login to view the page. I’ve used the following code from Link. The issue however is when the user logs in, he is taken to the home page rather than the page he was trying to visit. How can i solve this?
add_action('template_redirect','wpse16975_check_if_logged_in');
function wpse16975_check_if_logged_in(){
$pageid = 2295;
if(!is_user_logged_in() && is_page($pageid)) {
$url = add_query_arg(
'redirect_to',
get_permalink($pageid),
site_url('wp-login.php')
);
wp_redirect($url);
exit;
}}
You can use
wp_login_url()
.http://codex.wordpress.org/Function_Reference/wp_login_url
Change this:
To:
A similar URL will be assigned to the
$url
variable but the redirect_to parameter will be run throughurlencode()
first.