true ) ); } } /** * Removes the role from the current site. * * @return void */ public static function remove() { remove_role( self::ROLE ); } /** * Hooks into WordPress. * * @return void */ public function register() { add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 ); add_action( 'admin_menu', array( $this, 'trim_menu' ), 999 ); add_action( 'load-index.php', array( $this, 'redirect_dashboard' ) ); } /** * Sends report viewers to their report after login. * * @param string $redirect_to Requested redirect. * @param string $requested Original requested redirect. * @param \WP_User|\WP_Error $user Logged-in user. * @return string */ public function login_redirect( $redirect_to, $requested, $user ) { if ( $user instanceof \WP_User && $this->is_viewer_only( $user ) && ( '' === $requested || admin_url() === $redirect_to ) ) { return AdminLinks::url( AdminLinks::REPORTS ); } return $redirect_to; } /** * Hides the WordPress Dashboard menu item from report viewers. * * @return void */ public function trim_menu() { if ( $this->is_viewer_only( wp_get_current_user() ) ) { remove_menu_page( 'index.php' ); } } /** * Redirects report viewers away from the WordPress Dashboard. * * @return void */ public function redirect_dashboard() { if ( $this->is_viewer_only( wp_get_current_user() ) && current_user_can( Capabilities::VIEW_REPORTS ) ) { wp_safe_redirect( AdminLinks::url( AdminLinks::REPORTS ) ); exit; } } /** * Whether a user is a report viewer with no editing rights. * * @param \WP_User $user User. * @return bool */ private function is_viewer_only( \WP_User $user ) { return $user->exists() && in_array( self::ROLE, (array) $user->roles, true ) && ! user_can( $user, 'edit_posts' ); } }