1function redirect_user_tologin(){
2 global $post;
3 $post_slug = $post->post_name;
4
5 if(!is_user_logged_in()){
6 if($post_slug == 'my-account') { //can add multiple conditions
7
8 //create dynamic redirect page link
9 $redirect = urlencode(site_url().'/'.$post_slug);
10
11 //redirection
12 wp_safe_redirect(site_url().'/wp-login.php/?redirect_to=' .$redirect);
13 exit;
14 }
15 }
16}
17add_action('wp', 'redirect_to_login');
18