Check if WP_User_Query ‘include’ is empty

I think the problem here is that in the process of violating this rule, you’ve created confusion and problems:

do 1 thing per statement, 1 statement per line

Coupled with another problem:

Passing arrays to the APIs which get stored as serialised PHP ( security issue )

And another:

Always check your assumptions

it ignores the users that stored in ‘the_users’ user meta and print only current user.

That last one is the killer here. You never check for error values on get_user_meta, leading to errors. Users don’t start out with the_users meta, it has to be added.

Run through this code in your mind, e.g.:

$the_following_users=""; //get_user_meta($the_follower, "the_following_users", true);

if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
    $the_following_users[] = $user_follow_to;

Here there is no check on $the_following_users, which may not be an array at all, but a false or an empty string.

So lets fix the saving:

$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
    $the_following_user = array();
}

Then lets simplify the next part:

$the_following_users[] = $user_follow_to;

And fix the saving so that it’s not a security risk:

$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );

Finally, lets move to the frontend:

Firstly, we assume the get_user_meta works, but never check if this is true:

$args = array (
    'order'      => 'DESC',
    'include'  => get_user_meta($author->ID, 'the_following_users', true)
);

What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:

$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
    // the user follows nobody, or has not followed anybody yet!
} else {
    // turn the string into an array
    $include = explode( ',', $include );
    $args = array (
        'order'      => 'DESC',
        'include'  => $include
    );
    // etc...
}

A Final Note

Your loop looks like this:

foreach ( $users as $user ) {
    // Get users
}

But you never share the code inside the loop, which could be why you’re having issues. For example, the_author always refers to the author of the current post. If you want to display information about the $user, you would need to pass its ID, or user the public properties, e.g.

foreach ( $users as $user ) {
    // Get users
    echo esc_html( $user->first_name . ' ' . $user->last_name );
}

Leave a Comment