Protect Content Based on User Role
You can hide or show menu items or page content based on user roles that are assigned to your WordPress user.
Supported User Roles
You can use this feature for normal WordPress user roles. If you are using a custom plugin that has special roles, they may not work with this feature.
First, visit your WordPress admin, and go to a user. Click the "role" dropdown and see what role they are assigned. As you can see below, I have a user named andre with a role of "New Member."
Find User Role Slug
Next, I need to find the user role slug. For a single word like "Subscriber" or "Administrator" it's just the lowercase version of that word (subscriber, administrator). For most other roles, there is an underscore between the words, like new_member.
You can check the slug by installing the User Role Editor plugin, and going to Users => User Role Editor.
How It Works
For this feature to work, your user must have a role assigned, such as new_member. When the user logs in, the app will check for a user role, and you can use that to hide/show content as described below.
AppPresser does not handle assigning custom user roles for plugins. If you'd like to create a custom user role just for the app, you would need to:
- Add the custom user role to WordPress (you can use the User Role Editor plugin).
- Assign the role to members using custom code.
Hide or Show Menu Items
To show or hide menu items in either the side menu or the tab menu add "role-{user-role}" to the menu item's extra classes field.
Continuing with our example of a role called "new_member", you can add role-new_member to the extra classes of a menu item to only show this item to users that have that role.
On the right you can see how to use the default role of administrator.
|
Hide or Show Content in a Custom Page
Here is an example to show or hide content in a custom page based on user role. AppPresser 4 Only:
<div *ngIf="hasRole('new_member')">You are a new member</div> <div *ngIf="user?.roles"> <h3>Your Roles</h3> <div *ngFor="let role of user.roles">{{ role }}</div> </div>
Tip: Add the code above to a custom page and build your app to see what roles are assigned to a user. Do not use this code in production, it's just for testing!
To show your menu items on a custom page, and hide links to pages based on user role, make sure you have the latest code that looks something like this. AppPresser 4 Only:
<ion-grid> <ion-row> <ion-col size="6" *ngFor="let p of pages.all.items | slice:1" [ngClass]="p.extra_classes" [hidden]="p.show === false"> <ion-card (click)="pushPage(p)" class="menu-card"> <ion-card-title> <ion-icon *ngIf="p.class" name="{{p.class}}" size="large"></ion-icon> </ion-card-title> <ion-card-content>{{p.title}}</ion-card-content> </ion-card> </ion-col> </ion-row> </ion-grid>
AppPresser 3 apps should use user?.hasRole() instead of just hasRole() like this:
<div *ngIf="user?.hasRole('level-1')">Stuff here</div>