I’ve hacked together some code to create a sidebar widget for WordPress that displays all non-subscriber users (ie editors, contributors and admin) in a list.
It also displays a custom field for the users job title.
user_role
Custom fields are created via Advanced Custom Fields plugin.
Currently this works great, however there is now a requirement to hide specific users from the list. I have implemented another field; a true/false box. When ticked, it should display the user in the list.
user_hide
Currently, everything I have tried results in displaying no users, or all users.
Below is the foreach user in it’s original state that will only show users that don’t have a role as “subscriber”.
foreach($allUsers as $currentUser)
{
if(!in_array( 'subscriber', $currentUser->roles ))
{
$users[] = $currentUser;
}
}
Now somehow, it also needs to “AND if the custom field is true” but I have no idea how to get that but to work. In the database, under user meta, the key “author_hide” shows the vlaues “1” for true, or “0” for false.
I have tried the below but it still displays the same user list as the original despite having gone through all users and ticking/saving where appropriate:
$user_query = new WP_User_Query( array( 'meta_key' => 'author_hide', 'meta_value' => '1','meta_compare' => '==' ) );
foreach($allUsers as $currentUser)
{
if(!in_array( 'subscriber', $currentUser->roles ) && $user_query)
{
$users[] = $currentUser;
}
}
Any ideas?
Below is the current function:
function contributors() {
$allUsers = get_users('orderby=name&order=ASC');
$users = array();
echo '<ul class="authors-list">';
foreach($allUsers as $currentUser)
{
if(!in_array( 'subscriber', $currentUser->roles ))
{
$users[] = $currentUser;
}
}
foreach($users as $user)
{
?>
<li class="author-left author-light rounded-corners">
<div class="rounded-corners">
<div class="rounded-corners">
<a href="<?php echo get_author_posts_url( $user->ID ); ?>">
<strong><?php echo $user->display_name; ?></strong>
<br>
<?php $user_role = get_user_meta($user->ID, 'author_role', true); if($user_role != '') { echo $user_role; } ?>
</a>
</div>
</div>
<div class="pic">
<a href="<?php echo get_author_posts_url( $user->ID ); ?>"><?php echo get_avatar( $user->user_email, '50' ); ?></a>
</div>
</li>
<?php
}
echo '</ul>';
}
You can use the Advanced Custom Fields API to fetch the custom field for each user while you’re in the loop. Here’s how I would do it:
Note that Advanced Custom Fields requires that you prepend your User ID with the string
user_
when you callget_field()
so that the function knows you’re not trying to fetch a post.More info can be found in their documentation.