hey,
i'm using this in a view to filter posts by author:
add_shortcode("admin-list-of-authors", "admin_list_of_authors");
function admin_list_of_authors() {
$out = '<option value="">--choose--</option>';
$users = get_users();
foreach ($users as $user) {
$out .= '<option value="' . $user->ID . '">' . $user->display_name . '</a>';
}
return $out;
}
It works great - but is there an option to show not the display_name, but a custom field? such as my clinic-name? when I insert this instead of "display_name" i get nothing.
thx!
Hi Ido,
Thanks for asking! I'd be happy to help.
To get the value of a user's custom field through his/her ID, you can use "types_render_usermeta" function, from Types Fields API:
https://toolset.com/documentation/customizing-sites-using-php/functions/
Example:
$field_value = types_render_usermeta( "clinic-name", array( "user_current" => false, "user_id" => $user->ID ));
You can use this inside your shortcode's loop and you'll have the field's value for the current user in "$field_value".
I hope this helps and please let me know if you need any further assistance around this.
regards,
Waqar
thx Waqar!
I'm not trying to get the current user, I'm trying to get a list of all users.
It worked before, the only thing that I wanted to change was that the options in the select box will display not the username, but the custom field "clinic-name").
I tried:
add_shortcode("list-of-authors", "list_of_authors");
function list_of_authors() {
$field_value = types_render_usermeta( "clinic-name", array( "user_current" => false, "user_id" => $user->ID ));
$out = '<option value="">כולם</option>';
$users = get_users();
foreach ($users as $user) {
$out .= '<option value="' . $user->ID . '">' . $field_value . '</a>';
}
return $out;
}
But that gives me only the current user.
What did I do wrong?
Thx!
Ido
Hi Ido,
Thanks for writing back and sorry if my message caused confusion.
When I wrote "You can use this inside your shortcode's loop", I meant inside the "foreach { ... }" block.
( screenshot: enlace oculto )
That "foreach" block is cycling through the user's list one user per iteration, which means that in each loop's iteration "$user->ID" will return the ID of a different user in that list.
( this is what I referred to as the current user and not the currently logged-in user )
Note: with the current position of $field_value, you're only getting currently logged-in user's value because at that point $user->ID is not defined and "user_id" gets a blank value, and the "types_render_usermeta" function falls back to return the value from the currently logged-in user.
I hope this clarfies.
regards,
Waqar
Perfect, Waqar - thx! works like a charm 🙂