性价比最高的香港ASP、PHP主机提供商
做网站,就上凡科建站

掌握 WP_User_Query

Loading
0
Comodo SLL证书促销 - 免费ssl证书申请_ssl证书购买_ev ssl证书_https证书购买 - GDCA_数安时代

学习了本系列前面所有的内容后,我们就学完了 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?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' );
 
}
 
?>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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 与主查询(the Main Query)
下一篇:掌握 WP_Comment_Query
支付宝扫码打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

MetInfo | 最适合企业网站建设的cms系统

关于 倡萌

一个疯狂的 WordPress 爱好者,喜欢折腾 WordPress 主题,分享 WordPress 资源。如果你也喜欢 WordPress,欢迎和我一起交流!

发表评论