You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress函数中同时返回角色列表与角色数量?

How to Return Both Role List and Count in a Single WordPress Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:11:53