[wp-hackers] list users by (dynamic) meta value

John Blackbourn johnbillion+wp at gmail.com
Tue Oct 23 10:44:52 UTC 2012


On 23 October 2012 11:38, A5D <info at a5d.org> wrote:
> Hey Gavin,
>
> I'm presuming my cockney accent didn't come over so I'll try to explain clearer.
> ;)
>
> No, I don't have a load of pages created, that's what I'm trying to avoid.
> I could manually create the pages and run the query on each, individually, but then nothing will be dynamic (changes to meta_value will happen often and more pages will be required).
>
> What I am trying to do is use one template, with a custom query, that loads a list of users based on the contents of the meta_value field.
>
> So, I have:
> Users profile with a custom meta_field:
>
> <?php
> $args = array(
> 'role' => 'author' ,
> 'meta_key' => 'team',
> 'meta_value' => 'CONTENTS OF THIS FIELD DICTATE THE LIST OF USERS PRESENTED',
> 'order' => 'ASC',
> 'number' => 25,
> );
> $authors = get_users($args);
>    foreach($authors as $author){
>        $author_info = get_userdata($author->ID);
>        ?>
>        DO THE STUFF
>        <?php } ?>
>
> If the meta_value = Directors then a list of directors is presented etc.

Just use a variable from the query parameter, eg.
example.com/page?show_me=directors

Then:

$args = array(
'role' => 'author' ,
'meta_key' => 'team',
'meta_value' => stripslashes( $_GET['show_me'] ),
'order' => 'ASC',
'number' => 25,
);

If you want to order the users by the value of the meta value, then
set the 'orderby' argument to 'meta_value'. Eg:

$args = array(
'role' => 'author' ,
'meta_key' => 'team',
'meta_value' => stripslashes( $_GET['show_me'] ),
'orderby' => 'meta_value',
'order' => 'ASC',
'number' => 25,
);

If you wanted to get fancier with some pretty URLs you could add a
rewrite rule using add_rewrite_rule() [1] and use the 'query_vars'
filter to give you something like example.com/page/directors, and then
use get_query_var('show_me') instead of $_GET['show_me']. Shouldn't be
too difficult.

John

[1] http://codex.wordpress.org/Rewrite_API/add_rewrite_rule


More information about the wp-hackers mailing list