Redirect Users who aren't logged in, aren't post authors and aren't admin. Frontend

Very new to PHP and I'm trying to do the following through a snippets plugin but keep getting critical errors:

  • Restrict all non-logged in users to home, about and pricing pages. If attempting to access other pages, redirect to no-permission message page.
  • If user is logged in, allow them to only view posts on the front end if they are the post author. If attempted, redirect to no-permission page.
  • Admin has full read access on front end.

I've tried with plugins but nothing quite gives me what I want,

Any help is much appreciated, code below:

add_action( 'template_redirect', 'redirect_non_permitted_users' );

function redirect_non_permitted_users () {
     $userID = get_user_id();
     $authorID = get_the_author_meta(ID);

    if(current_user_can('manage_options')){
 
    }

    elseif( $userID  $authorID || ! is_user_logged_in() || ! is_front_page() || ! is_page('about') || ! is_page('pricing')){
        wp_redirect('https://www.example.com/no-permission/'); 
    exit;
    }   
}

Topic template-redirect wp-redirect Wordpress

Category Web


This is seems to do what I want. Issue was $userID conflicting with $authorID on the 'no-permission' page causing a redirect loop.

add_action( 'template_redirect', 'redirect_non_permitted_users' );

function redirect_non_permitted_users () {
  if (is_admin()) return;
  $userID = get_current_user_id();
  global $post;
  $authorID = absint($post->post_author);

  if (is_page('no-permission') || current_user_can('manage_options')){
  return;
  }  

  if( ($userID !== $authorID || ! is_user_logged_in()) && ! 
  is_front_page() && ! is_page('about') && ! is_page('pricing')){
    wp_redirect('https://www.example.com/no-permission/');
    exit;
  }
}

get_user_id() is not a function so you'll get an error for that. Additionally, you can get the author id by calling the $post global and accessing the property post_author

add_action( 'template_redirect', 'redirect_non_permitted_users' );

function redirect_non_permitted_users () {
    if (is_admin()) return;
    $userID = get_current_user_id();
    global $post;
    $authorID = absint($post->post_author);
    
    if( $userID !== $authorID && ! is_user_logged_in() && ! is_front_page() && ! is_page('about') && ! is_page('pricing')){
        wp_redirect('https://www.example.com/no-permission/');
        exit;
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.