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';
}
wp_reset_postdata();
return $results;
}
add_shortcode( 'list_users', 'users_from_meta' );
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';
}
wp_reset_postdata();
return $results;
}
add_shortcode( 'list_users', 'users_from_meta' );
Share
Improve this question
asked May 10, 2019 at 17:18
MichaelMichael
2811 silver badge14 bronze badges
1 Answer
Reset to default 1It'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.