0

I am currently using the wp_roles() function to retrieve all user roles available like this:

<?php
  foreach (wp_roles()->get_names() as $role) {
    echo translate_user_role( $role );
  }
?>

How would I retrieve an array/list of all custom roles that I've created without the default roles (Administrator, Editor, Subscriber, etc) included?

2
  • what does translate_user_role do? Wouldn't it be easier to use __( ... ), then you could use the standard core localisation system and the default roles would auto-translate
    – Tom J Nowell
    May 30, 2022 at 9:25
  • @TomJNowell Good point. I'll switch that part up. But how do I retrieve only custom roles and exclude default WordPress roles?
    – AndrewL64
    May 30, 2022 at 11:02

1 Answer 1

0

So I ended up using a combination of the array_filter function and the in_array function to retrieve all custom roles like this:

<?php

  function check_roles($userRole) {
    $default_roles = array('Administrator', 'Editor', 'Author', 'Contributor', 'Subscriber');
    if (!in_array($userRole, $default_roles)) {
      return $userRole;
    }
  }

  $all_roles = wp_roles()->get_names();
  $custom_roles = array_filter($all_roles, 'check_roles');

  foreach ($custom_roles as $role) {
    echo $role;
  }

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.