Redirect non post author to homepage
-
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.
- The topic ‘Redirect non post author to homepage’ is closed to new replies.