如何在WordPress函数中同时返回角色列表与角色数量?
Absolutely! You don't need to write an extra independent function—there are a couple of straightforward ways to make this function output both the role list and count exactly like your example.
Option 1: Output Directly Inside the Function
Since you're already calling the function to display results, you can skip returning values entirely and handle the output directly within the function. This is the simplest approach for your specific use case:
function all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); $role_count = count($the_roles); // Use count() instead of looping to increment, it's more efficient // Print each role on a new line foreach($the_roles as $role) { echo $role . '<br />'; } // Print the final count echo $role_count; } // Just call the function directly to get your desired output all_the__roles();
When you run this, it will output exactly what you asked for:
Administrator
Editor
Client
3
Option 2: Return an Array for Flexibility
If you want more control over how you use the role list and count later (e.g., using them separately elsewhere in your code), you can return an associative array containing both values:
function all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); $role_list = ''; foreach($the_roles as $role) { $role_list .= $role . '<br />'; } // Return an array with both the formatted list and the count return [ 'role_list' => $role_list, 'role_count' => count($the_roles) ]; } // Call the function and output the values as needed $role_data = all_the__roles(); echo $role_data['role_list']; echo $role_data['role_count'];
This way, you can reuse the role list or count individually without modifying the core function logic later.
内容的提问来源于stack exchange,提问作者User_FTW

