Display posts of certain categories to specific user roles

The problem consists of three parts: getting the current user data, linking that to a category and retrieving and displaying the posts. You can include these snippets on a custom page template, which you assign to the ‘My homework’-page.

Below these three sub-answers, I share some additional suggestions on ways of making this more user-friendly / user-manageable.

Getting the user data

This is done very easily using wp_get_current_user. This yields a WordPress User object, from which you can retrieve the roles using $current_user->roles (assuming you have set $current_user = wp_get_current_user();). This yields an array. I’m assuming the users only have one role, so that the first element in that array is the element we’re checking against.

Linking users to categories

You can do this using an if-elseif-statement, as follows.

$roles = $current_user->roles;

if ($roles[0] == 'role'){
    $category_name="category-name";
}elseif ($roles[0] == 'other-role'){
    $category_name="other-category-name";
}

You can extend this as you like, by adding additional elseif-clauses. Replace role (and other-role) by the slugs of the roles, and category-name and other-category-name by the slugs of the categories.

Retrieving and displaying the posts

Using $category_name in the arguments of a WP_Query limits the result that query retrieves to the categories.

$qrt_args = array(
    'category_name' => $category_name
);

$posts = new WP_Query( $qry_args ); 

You can now use $posts in a regular loop and display the results.

Other ideas

Although the code above should work (haven’t tested it), it requires you to edit code in order to make adjustments. That might be less convenient, for example if you at some point in time, are unavailable to make these changes.

Another option is to create a post for each student, subsequently assign the relevant category (or categories) to that post and set the author as the student. This way, you can match students and categories in the WordPress Dashboard. Also, this provides a little more flexibility and robustness, for example to assign multiple categories to the same student. (The code posted above assumes only one category.) Of course, this will also display the post you’ve used to set up the match on the page with homework problems, but you can use that to your benefit (“Hey John, please find your homework problems below”). It is, however, also possible to prevent that from happening using an additional category or tag.

Another option, which is even nicer but also a bit more difficult to implement, is to create a new usermeta-field in which you save which categories of posts that user should be able to see.

Please note this does not (yet) provide a solution to this part of your problem:

I also want to restrict each author to using only the categories I assign them rather than choosing from all the categories available.

tech