当前位置:首页>WordPress建站>WordPress开发>掌握 WP_User_Query

掌握 WP_User_Query

学习了本系列前面所有的内容后,我们就学完了 WP_Query 这个类,但不意味着我们这个系列的结束!是时候来见见 WP_Query 的兄弟姐妹类了:WP_User_QueryWP_Comment_QueryWP_Meta_QueryWP_Date_Query。

本部分我们将来学习如何使用 WP_User_Query 类在 WordPress 中查询用户。

注:由于时间精力有限,本教程没办法翻译分享,希望朋友们可以加入我们,帮助我们进行翻译,有小酬谢,有意者请联系倡萌QQ 745722006(注明:教程翻译)。

以下为原文:http://code.tutsplus.com/tutorials/mastering-wp_user_query–cms-23204

After all those previous parts, we’re done going through the WP_Query class—but that doesn’t mean that we’re done with the series! It’s time to meet WP_Query‘s brother and sister classes: WP_User_Query,WP_Comment_Query, WP_Meta_Query and WP_Date_Query.

In this part, we’re going to learn about using the WP_User_Query class to query users in WordPress.

Let’s begin!

What Is WP_User_Query?

You probably get the idea of what WP_User_Query is by merely reading its name. Yes, nobody would expect to see WP_User_Query working with the “Tag Cloud” widget—it’s a class that runs queries about users in WordPress.

Let’s see what WordPress Codex says about the WP_User_Query class:

WP_User_Query is a class, defined in wp-includes/user.php, that allows querying WordPress database tables ‘wp_users‘ and ‘wp_usermeta‘. This class was introduced in Version 3.1 and as a result, the WP_User_Search class got deprecated.

In essence, we can say that “WP_User_Query is WP_Query for users”. It works with wp_users and wp_usermeta to query users and their metadata.

Now, let’s see what’s under the hood and learn about WP_User_Query‘s properties, methods and parameters. Then we’ll see how it works by going through a few examples.

Quick Tip: We’ve covered this while introducing the properties and methods of the WP_Query class, but let me say it again as a quick reminder: “Properties” and “methods” are merely “variables” and “functions” that are defined inside a PHP class.

Properties of WP_User_Query

There are only seven properties to learn about in the WP_User_Query class. Remember: These should NOT be used to change their values. You can fetch their values, but it’s better not to alter them.

$query_vars

This property stores an associative array of query variables and their values.

$results

This property has the number of found items (users in this case) for the query.

$query_fields

This property, similar to the following properties, stores the SQL clauses for the return fields.

$query_from

This property stores the FROM clause for the query.

$query_where

This property stores the WHERE clause for the query.

$query_orderby

This property stores the ORDERBY clause for the query and is used to order the list of users returned.

$query_limit

This property stores the LIMIT clause for the query and is used to limit the number of users returned.

Methods of WP_User_Query

Remember the methods of the WP_Query class? Well, this class has only four methods and they work just like the methods of WP_Query. Let’s quickly see why each one exists.

The get() Method

This method simply fetches a query variable from the query.

The set() Method

Contrary to the one above, this method sets a query variable instead of getting it.

The get_results() Method

Unlike WP_Query, the WP_User_Query class doesn’t work with a “loop”. Instead, you need to use theget_results() method to get the query results and work on them.

The get_total() Method

This little method returns the total number of items (users) for the query.

Parameters of WP_User_Query

Like the WP_Query class, WP_User_Query has parameters that you need to know about. But while WP_Query has a large number of parameters (more than 50!), WP_User_Query has only 17 parameters to worry about—and they’re very similar to the ones in WP_Query, so if you’re familiar with those, it shouldn’t be any hassle learning these ones.

  • blog_id: An integer to specify a blog’s ID in multisite networks. Defaults to the current blog.
  • role: A string to state a user role. Accepts subscriber, author, contributor, author, editor, administrator, and any custom-created user role.
  • include: An array of user IDs to include in the query.
  • exclude: An array of user IDs to exclude from the query.
  • search: A string value to search for in the fields of the wp_users table.
  • search_columns: An array of columns of the wp_users table. Accepts ID, user_login, user_url, user_email, and user_nicename.
  • orderby: A string to state how to sort the returned users. Accepts ID, display_name, name/user_name,login/user_login, nicename/user_nicename, email/user_email, url/user_url, registered/user_registered,post_count, and meta_value. Defaults to login.
  • order: A string to set the order to ascending (ASC) or descending (DESC).
  • offset: An integer to specify the number of users to pass over.
  • number: An integer to set the number of users to return.
  • count_total: A boolean (TRUE/FALSE) to state whether to count the total number of users found.
  • fields: A string or array to decide which fields to return from the wp_users table.
  • who: A string (either authors or all, which is the default value) to state which users to query.
  • meta_key: A string to state a custom user meta field key.
  • meta_value: A string to state a custom user meta field value.
  • meta_compare: A string to set an operator to test the 'meta_value' parameter. Accepts '=', '!=', '>','>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS', and 'NOT EXISTS'. Defaults to '='.
  • meta_query: An array to create a full meta data query, using keys similar to the ones above:
    • key: A string to set a custom field key.
    • value: A string or an array to set a custom field value (or values).
    • compare: A string to set the compare operator. Accepts the same values as meta_compare above.
    • type: A string to set the custom field type. Accepts NUMERIC, BINARY, CHAR, DATE, DATETIME, DECIMAL,SIGNED, TIME, and UNSIGNED. Defaults to CHAR.

Trying Out WP_User_Query With a Few Examples

Now we’ve seen how WP_User_Query works, let’s do a couple of examples to learn how to use it.

Listing All Editors Except Lisa

Let’s say you want to list your editors to your readers, but you remember that one of your editors, Lisa, has agreed to work with you on condition of anonymity, so you need to leave her out in the “Editors” list. Here’s how you construct the query:

<?php
 
// Add Lisa's user id,  14, in an array.
$exclude_list = array( 14 );
 
$args = array(
    'role' => 'Editor',
    'exclude' => $exclude_list
);
 
// Custom query.
$my_user_query = new WP_User_Query( $args );
 
// Get query results.
$editors = $my_user_query->get_results();
 
// Check for editors
if ( ! empty( $editors ) ) {
 
    echo '<ul class="editors-list">';
 
        // Loop over editors.
        foreach ( $editors as $editor ) {
     
            // Get each editor's data.
            $editor_info = get_userdata( $editor->ID );
     
            // Show editor's name.
            echo '<li>' . $editor_info->display_name . '</li>';
     
        }
 
    echo '</ul>';
 
} else {
 
    // Display "no editors found" message.
    echo __( 'No editors found!', 'tutsplus' );
 
}
 
?>

Search for Gmail Users Among Your Authors

Let’s say you want to collect email addresses of your authors which use a Gmail address. Here’s what you do:

<?php
 
// Setup arguments.
$args = array(
    // Search for authors only.
    'who' => 'authors',
    // Search for email addresses ending with `@gmail.com`.
    'search' => '*@gmail.com',
    // Search the `email` field only.
    'search_columns' => array( 'email' ),
    // Return the `email` field only.
    'fields' => 'email'
);
 
// Custom query.
$my_user_query = new WP_User_Query( $args );
 
// Get query results.
$gmailers = $my_user_query->get_results();
 
?>

Wrapping Everything Up

As you can see, there are just a few differences between WP_Query and WP_User_Query, and the differences actually make WP_User_Query easier to understand. I hope I helped you learn about this neat class of WordPress.

Do you have anything to add to this article? Share your thoughts with us in the Comments section below. And if you liked the article, don’t forget to share it with your friends.

See you in the next part of the series!

您已阅读完《掌握 WP_Query(共19篇)》专题的第 15 篇。请继续阅读该专题下面的文章:

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
欢迎关注WordPress大学公众号 WPDAXUE
WordPress开发

结合 WP_Query 与主查询(the Main Query)

2016-5-8 8:21:50

WordPress开发

掌握 WP_Comment_Query

2016-5-9 7:56:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索