Trying to display a list of users that match certain criteria using a shortcode with parameters. Here is what I have so far, but for some reason it does not display anything. I am pretty new at this stuff, so if anybody has examples of changes that would be very helpful. Thanks in advance.

 * Shortcode for Listing Users from Meta Data
 * Usage: [list_users key="green-eyes" value="Yes" userrole="x-genes,y-genes"]
function users_from_meta($atts) {
    $atts = shortcode_atts( array(
        'key'   => '',
        'value' => '',
        'userrole'  => '',
    ), $atts );
    $user_query = new WP_User_Query( array( 
        'meta_key' => $atts['key'],
        'meta_value' => $atts['value'],
        'role__in'    => wp_parse_list( $atts['userrole'] ),
    ) );
    $users = $user_query->get_results();
    if (!empty($users)) {
        $results = '<ul>';
        foreach ($users as $user){
            $results = '<li>' . $user->display_name . '</li>';
        $results =  '</ul>';
    } else {
        $results =  'No users found';
    return $results;
add_shortcode( 'list_users', 'users_from_meta' );

It's a small coding mistake..

It's not displaying anything because when there are results, the end output is always a </ul> because you're always overwriting the $results and not appending output to the variable:

$results = '<ul>';
foreach ($users as $user){
    $results = '<li>' . $user->display_name . '</li>';
$results = '</ul>';

So the proper code is:

$results = '<ul>';
foreach ($users as $user){
    $results .= '<li>' . $user->display_name . '</li>';
$results .= '</ul>';

And there's no need to call wp_reset_postdata() because in your code, there's no call to any functions which modifies the global $post object/data.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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