shortcode - How to list users by custom field?

admin2025-01-07  5

I have a custom user field in the standard database, called company. I want to output on to a page the usermeta info only of users whose company matches Widgets Inc ...

How do I do that?

What I'd really like to be able to do is avoid putting this in a page template and instead create a shortcode to list user info, with functionality to limit by field attribute - ie. {listusers company="Widgets Inc"}

But I don't know how to do that.

I have a custom user field in the standard database, called company. I want to output on to a page the usermeta info only of users whose company matches Widgets Inc ...

How do I do that?

What I'd really like to be able to do is avoid putting this in a page template and instead create a shortcode to list user info, with functionality to limit by field attribute - ie. {listusers company="Widgets Inc"}

But I don't know how to do that.

Share Improve this question edited Oct 11, 2013 at 10:17 Eugene Manuilov 11.4k4 gold badges44 silver badges50 bronze badges asked Oct 11, 2013 at 9:56 Robert AndrewsRobert Andrews 98819 silver badges42 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

To fetch users with certain meta field, you can use WP_User_Query class. Check codex manual for it.

So you can create a custom shortcode like this:

add_shortcode( 'listusers', 'wpse8170_listusers' );
function wpse8170_listusers( $atts, $content = '' ) {
    $atts = shortcode_atts( array( 'company' => false ), $atts );

    if ( empty( $atts['company'] ) ) return $content;

    $query = new WP_User_Query( array(
        'meta_key' => 'company', 
        'meta_value' => $atts['company'],
    ) );

    ob_start();

    // render your users list here

    return ob_get_clean();
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259289a578.html

最新回复(0)