• Resolved bagwis

    (@bagwis)


    Hello,

    I am currently working to a project wherein I need to have a function that will redirect the current user if he/she tries to view the custom post type which he/she doesn’t own. The reason is that my client requires me to make this singular page to be accessible only to the admin and post author since it contains personal information.

    I’ve searched for some ideas but I haven’t found any so I referred to the codex and found this template_redirect. So here is my current code

    function check_the_author(){
        global $current_user;
    	$user_id = get_current_user_id();
    	$post_author = get_the_author_meta('ID');
    	if( is_singular('my_post_type') && $user_id != $post_author ){
    		wp_redirect( home_url() );
    		exit();
    	}
    }
    do_action( 'template_directory', 'check_the_author' );

    Unfortunately, even if the post author is viewing his own post, it still being redirected. So I tried to interchange the code and make it similar to this

    function check_the_author(){
        global $current_user;
    	$user_id = get_current_user_id();
    	$post_author = get_the_author_meta('ID');
    	if( is_singular('my_post_type') && $user_id == $post_author ){
    
    	}
    	else{
    		wp_redirect( home_url() );
    		exit();
    	}
    }
    do_action( 'template_directory', 'check_the_author' );

    but the result for this second code is simply nothing, I mean if a user tries to view others’ posts he can access it and doesn’t get redirected. I already posted here to ask for some assistance cause I’ve been working with this for more or less 3 hours now. Thank you, by the way the website is still on my localhost so I can’t provide a link.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    get_the_author_meta('ID') needs to be inside the loop to return the correct value, the ‘template_directory’ action is not in the loop. But if you used a hook inside the loop, I think the redirect will fail. I’m not sure though, try hooking the ‘loop_start’ action to confirm.

    If I’m right, I’m not sure how to determine what post is being queried early enough for the redirect to work. The post is needed in order to determine the author (duh!). You may have to settle for throwing a permissions error once the post is known rather than do a redirect.

    Thread Starter bagwis

    (@bagwis)

    Hello bcworkz, thanks for the idea that get_author_meta(‘ID’) needs to be inside the loop so I came up with a solution.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Redirect non post author to homepage’ is closed to new replies.