0

I am working on a wordpress site where I have created a directory page(authors.php) that lists all users and certain author meta.

It works fine however I am trying to figure out how to only show users that have the required author meta filled out.

I've tried many different things but have not been able to achieve what I need. Here is my code

<?php
    $order = 'user_nicename';
$users = $wpdb->get_results("SELECT * FROM $wpdb->users ORDER BY $order"); // query users

    foreach($users as $user) : // start users' profile "loop"
    ?> 

Everything else I try does not return any results. Is there a way to only select users with specific author meta fields filled out? Any help is appreciated, thanks.

1 Answer 1

1

You're probably better off to use get_users which returns an array of

<?php
// get all users, regardless of roll.  If you do need to restrict by
// role you can use the `role` argument: get_users(array('role' => 'author'));
$uses = get_users(array('orderby' => 'nicename'));

foreach ($users as $user) {
   // do stuff with $user, will have all the usual stuff, ID, user_email, etc
   echo '<p>', esc_html($user->ID), '</p>';
}

Alternatively, you can use the all_with_meta argument for the fields argument of get_users and get an array of WP_User objects back:

<?php

$users = get_users(array('fields' => 'all_with_meta'));

foreach ($users as $user) {
   // $user will be a WP_User object.
}

Is there a way to only select users with specific author meta fields filled out?

You can do this with get users as well! Just use the meta_query argument, which looks the same as WP_Query's meta_query argument.

<?php
$users = get_users(array(
    'meta_query' => array(
        array( 
            'key'   => 'whatever_your_meta_key_is',
            'value' => 'the_meta_value_you_want',
        )
     ),
));

foreach ($users as $user) {
    // do stuff with $user
}
3
  • Thanks for the answer! However Im having some trouble getting things to work. Here's what I have - <?php $args = array( 'fields' => 'all_with_meta', 'meta_query' => array( array( 'key' => 'first_name' // the meta field (or key) we want to target ) )); $users = get_users($args); foreach ($users as $user) : ?> //my content <?php endforeach; // end of the users' profile 'loop' ?>
    – 730wavy
    Commented Mar 5, 2013 at 7:47
  • Either Im not understanding correctly or get_users is just not working for me. Is there anyway to do modify my original code to only show users with specific custom fields?
    – 730wavy
    Commented Mar 17, 2013 at 0:19
  • Thanks I figured it out. There was a conflict caused by the plugin Profile Builder Pro.
    – 730wavy
    Commented Apr 2, 2013 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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