Ever since WordPress implemented custom post types a whiles back, the use of WP_Query
to retrieve posts based on custom criteria has become standard practice. Listing comments has not become so widespread for some reason, despite the availability of the WP_Comment_Query
class.
自从WordPress实施了一段时间以来的自定义帖子类型以来,使用WP_Query
根据自定义条件检索帖子已成为标准做法。 尽管可以使用WP_Comment_Query
类,但由于某种原因,列表注释并未变得如此普遍。
WP_Comment_Query
allows theme and plugin authors to retireve post comments using a standardized interface. The days of ugly direct database queries are gone. We can now use modular and readable arguments to do our bidding.
WP_Comment_Query
允许主题和插件作者使用标准化界面撤消帖子评论。 丑陋的直接数据库查询时代已经一去不复返了。 现在,我们可以使用模块化和易读的参数进行出价了。
为什么我们要列出评论? (Why Should We List Comments?)
You might be thinking: why? The programmer in me would answer: because we can! This seems a little silly, but there is a deeper meaning hidden there. A framework is only any good if it is flexible and modular. A modular framework should allow wasy and standardized access to its information. Being able to retrieve comments according to your custom criteria is a part of this mindset.
您可能在想:为什么? 我里面的程序员会回答:因为我们可以! 这似乎有些愚蠢,但其中隐藏着更深的含义。 框架只有灵活且模块化,才有好处。 模块化框架应允许对信息进行浪费和标准化的访问。 能够根据您的自定义条件检索评论是这种思维方式的一部分。
The pragmatist in me looks to specific use-cases to answer the question. Using WP_Comment_Query
you can build a page where users can browse your site comments according to date, popularity and custom featured comments.
我内的实用主义者着眼于特定的用例来回答这个问题。 使用WP_Comment_Query
您可以构建一个页面,用户可以在其中根据日期,受欢迎程度和自定义特色评论浏览您的站点评论。
If you're building user profiles you may want to show a particular user's comments, or comments related to a user's favorited articles.
如果要构建用户个人资料,则可能要显示特定用户的评论,或与用户喜欢的文章相关的评论。
WP_Comment_Query如何工作 (How WP_Comment_Query Works)
A comment query is usually used in conjunction with a loop that lists the comments that are retrieved. A full implementation of a query and loop would look something like this:
注释查询通常与列出检索到的注释的循环结合使用。 查询和循环的完整实现如下所示:
// Arguments for the query
$args = array();
// The comment query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// The comment loop
if ( !empty( $comments ) ) {
foreach ( $comments as $comment ) {
echo '<p>' . $comment->comment_content . '</p>';
}
} else {
echo 'No comments found.';
}
As you can see it isn't too complicated. The only things we need to be aware of are the arguments we can use that are passed to the query()
method on row 6.
如您所见,它并不太复杂。 我们唯一需要了解的是传递给第6行的query()
方法的参数。
通过邮件限制评论 (Restricting Comments By Post)
The most obvious way of restricting comments to a certain post is to use the post_id
parameter. By supplying a post's ID you can make sure only comments related to that post appear.
将评论限制为特定帖子的最明显方法是使用post_id
参数。 通过提供帖子的ID,您可以确保仅显示与该帖子相关的评论。
You could also list comments based on multiple posts. This could be useful if you want to show comments for two very closely related posts. In this case supply an array of post IDs to the post__in
parameter.
您也可以根据多个帖子列出评论。 如果您想显示两个非常相关的帖子的评论,这可能会很有用。 在这种情况下,请为post__in
参数提供一个帖子ID数组。
$related_posts = array( 12, 833, 229, 38 );
$args = array(
'post__in' => $related_posts
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
There are a bunch of post-related properties you can use, here's a shortlist:
您可以使用许多与帖子相关的属性,这是一个简短列表:
post_id
: Retrieves comments for a specific IDpost_id
:检索特定ID的注释post__in
: Retrieves comments for an array of postspost__in
:检索一系列帖子的评论post__not_in
: Retrieves comments for all posts except those in the supplied arraypost__not_in
:检索所有帖子的注释(提供数组中的注释除外)post_status
: Retrieves comments for posts with the given statuspost_status
:检索具有给定状态的帖子的评论post_type
: Retrieves comments for the given post typepost_type
:检索给定帖子类型的评论post_name
: Post name to retrieve comments forpost_name
:帖子名称以检索评论post_parent
: Retrive comments for posts with the given parentpost_parent
:检索具有给定父级的帖子的评论
You can choose to mix an match these parameters of course. You could retrieve comments for all posts which have a specific parent but are not in a given set:
您可以选择混合匹配这些参数。 您可以检索具有特定父级但不在给定集中的所有帖子的评论:
$unwanted = array( 3, 6, 10 );
$args = array(
'post__not_in' => $unwanted,
'post_parent' => 223
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
按作者限制评论 (Restricting Comments By Author)
Similarly to post restrictions you can use the user_id
parameter to list a specific user's comments. You can also use author__in
and author__not_in
to provide inclusion/exlcusion arrays.
与发布限制类似,您可以使用user_id
参数列出特定用户的评论。 您还可以使用author__in
和author__not_in
提供包含/排除数组。
Another great method of listing comments is to use author email addresses. Many comments will be submitted by non-registered users, in which case grabbing them by email is easy:
列出评论的另一种很好的方法是使用作者的电子邮件地址。 许多评论将由非注册用户提交,在这种情况下,通过电子邮件轻松获取它们:
$email = array( 'awesomecommenter@email.com' );
$args = array(
'author_email' => $email
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
To recap let's go through all the user parameters again:
回顾一下,让我们再次遍历所有用户参数:
user_id
: Retrieves comments by a specific useruser_id
:检索特定用户的评论author__in
: Retrieves comments by a set of usersauthor__in
:检索一组用户的评论author__not_in
: Retrieves all comments except from the given usersauthor__not_in
:检索给定用户以外的所有评论author_email
: Retrieves comments by user with the given emailauthor_email
:使用给定的电子邮件检索用户的评论
其他简单评论限制 (Other Simple Comment Restrictions)
There are a bunch of comment-based restrictions you can add, from dates to comment types and searches. Here's a full list with some examples below:
您可以添加一堆基于注释的限制,从日期到注释类型以及搜索。 以下是一些示例的完整列表:
comment__in
: Retrieves comments with the given IDscomment__in
:检索具有给定ID的评论comment__not_in
: Retrieves all comments except ones with the given IDscomment__not_in
:检索除具有给定ID的注释以外的所有注释include_unapproved
: Retrieved comments will include unapproved ones from the given users (ID or email)include_unapproved
:检索到的评论将包括来自给定用户(ID或电子邮件)的未批准评论karma
: Karma score to retrieve comments forkarma
:karma
分数以检索有关的评论search
: Retrieve comments which match the given search stringsearch
:检索与给定搜索字符串匹配的注释status
: Retrieve comments with the given status (accepts: hold, approve, all or custom status)status
:检索具有给定状态的注释(接受:保留,批准,全部或自定义状态)type
: The comment type to return ( comment, pings or custom type )type
:要返回的评论类型(评论,ping或自定义类型)type__in
: Retrieves comments from the given typestype__in
:检索给定类型的注释type__not_in
: Retrieves comments excluding the given typestype__not_in
:检索不包含给定类型的注释
Using these parameters we could list a custom comment type which contains the term "kazoo".
使用这些参数,我们可以列出包含术语“ kazoo”的自定义注释类型。
$args = array(
'type' => 'review',
'search' => 'kazoo'
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
基于日期的查询 (Date Based Queries)
WP_Comment_Query
supports date based restrictions using WP_Date_Query
which is used in regular post queries as well. This class allows you do add flexible date restrictions to any query easily, here's an example:
WP_Comment_Query
支持使用WP_Date_Query
基于日期的限制,该限制也用于常规的帖子查询中。 此类允许您为任何查询添加灵活的日期限制,例如:
$args = array(
'type' => 'review',
'date_query' => array(
array(
'after' => 'January 1st, 2014',
'before' => array(
'year' => 2014,
'month' => 7,
'day' => 01,
),
),
),
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
The date query is an array of arrays containing information that describes a date interval. This one is pretty self explanatory and shows how you can supply a date as text, or as an array. In the end, this query will return all comments posted in the first half of 2014.
日期查询是一个包含描述日期间隔信息的数组数组。 这是一个很好的自我解释,展示了如何以文本或数组形式提供日期。 最后,此查询将返回2014年上半年发布的所有评论。
You can use the WP_Date_Query
class to grab posts from a single date, from a range or combine it with other parameters to get comments posted a week ago and modified within the past 2 days.
您可以使用WP_Date_Query
类从单个日期,某个范围抓取帖子,或者将其与其他参数结合使用,以获取一周前发布的评论,并在过去两天内进行修改。
Regretfully this class doesn't have very good documentation on its own. You can find a bunch of examples in the date parameters for WP_Query.
遗憾的是,此类本身没有很好的文档。 您可以在WP_Query的日期参数中找到很多示例。
元查询 (Meta Queries)
Meta queries are powerful parameters that allow you to constrict results based on the data in the comment_meta
table. This is extremely useful for custom implementations where comments are used for reviews for example.
元查询是功能强大的参数,可让您根据comment_meta
表中的数据来缩小结果范围。 例如,对于将评论用于评论的自定义实现,这非常有用。
$args = array(
'type' => 'review',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'design',
'value' => '4',
'type' => 'numeric',
'compare' => '>='
),
array(
'key' => 'features',
'value' => '4',
'type' => 'numeric',
'compare' => '>='
)
)
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
This example shows how you can query for reviews which rated the product and features 4 or better. As you can see, multiple meta queries were added. The relation
parameter dictates how the query takes these into account. An AND
type relation makes sure both are true, an OR
type relation makes sure at least one is true.
本示例说明了如何查询对产品和功能评分为4或更高的评论。 如您所见,添加了多个元查询。 relation
参数指示查询如何将这些因素考虑在内。 AND
类型关系可确保两者都为真, OR
类型关系可确保至少一个为真。
This is followed by two arrays which define the meta key, it's value, and how we are comparing it. The value may also be an array if you are using a proper comparison operator (IN
,NOT IN
,BETWEEN
,NOT BETWEEN
,EXISTS
orNOT EXISTS
).
接下来是两个数组,它们定义了元键,它的值以及我们如何比较它。 如果您使用适当的比较运算符( IN
, NOT IN
, BETWEEN
, NOT BETWEEN
, EXISTS
或NOT EXISTS
),则该值也可能是数组。
The type can also be important, especially in distinguishing between text and numbers. The following are available: NUMERIC
, BINARY
, CHAR
, DATE
, DATETIME
, DECIMAL
, SIGNED
, TIME
, UNSIGNED
.
类型也很重要,尤其是在区分文本和数字时。 提供以下选项: NUMERIC
, BINARY
, CHAR
, DATE
, DATETIME
, DECIMAL
, SIGNED
, TIME
, UNSIGNED
。
订购和返回数据 (Ordering And Returning Data)
There are a couple of parameters that help us organize returned results, limit their number and determine exactly what data is returned for our comments. Here's a quick list with all of them:
有两个参数可帮助我们组织返回的结果,限制其数量并确定要返回的数据以供我们注释。 这是所有这些的快速列表:
count
: Set to true to return a comment count or false to return an array of commentscount
:设置为true返回评论数,设置为false返回评论数列fields
: Set toids
to return comment ID only or false to grab everythingfields
:设置为ids
来唯一的评论ID或假返回抢一切number
: Sets the number of comments to returnnumber
:设置要返回的评论数offset
: Use an offset when grabbing comments from the databaseoffset
:从数据库中获取注释时使用偏移量orderby
: The database column to order the comments byorderby
:按以下顺序排序注释的数据库列order
: Sets the direction of ordering -ASC
orDESC
order
:设置订购方向ASC
或DESC
Using the parameters above we could limit our results to the second three reviews ordered by the meta_value
for the rating:
使用上面的参数,我们可以将结果限制为由meta_value
排序的后三条评论:
$args = array(
'type' => 'review',
'meta_key' => 'rating',
'orderby' => 'meta_value',
'offset' => 3
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
WP_Comment_Query问题 (Problems With WP_Comment_Query)
As a quick aside I thought I'd mention an issue with this class: inconsistency. You may frequently hear that the WordPress codebase is a mess. This is a bit of an exageration but the state of WP_Comment_Query
is a good example of the truth in it.
暂时我想提到一个关于此类的问题:不一致。 您可能经常听到WordPress代码库一团糟。 这有点夸张,但是WP_Comment_Query的状态是其中WP_Comment_Query
的一个很好的例子。
This class was made to look like WP_Query
but it really isn't. When you list posts you use a loop with function like have_posts()
and the_post()
. With WP_Comment_Query
you use a regular loop. It would be better if we could use the same format with have_comments()
and the_comment()
.
此类看起来像WP_Query
但实际上并非如此。 当您列出帖子时,可以使用具有have_posts()
和the_post()
类的函数的循环。 通过WP_Comment_Query
您可以使用常规循环。 如果我们可以将相同的格式用于have_comments()
和the_comment()
会更好。
Parameters are also all over the place. The documentation doesn't list all of them and there are tons of duplicate parameters as well. Take a look at the source code for the full list.
参数也无处不在。 该文档没有列出所有这些参数,并且还有大量重复的参数。 查看完整列表的源代码 。
You can get authors with post_author__in
or author__in
. The include_unapproved
property is completely misleading, status does not have a status__in
type parameter and the parent
parameter really should be called comment_parent
to fall in line with WP_Query
. Not to mention that WP_Query
itself should be named WP_Post_Query
to maximize modularity.
您可以使用post_author__in
或author__in
获得作者。 include_unapproved
属性完全具有误导性,status在类型参数中没有status__in
并且确实应将parent
参数称为comment_parent
以与WP_Query
。 更不用说WP_Query
本身应该被命名为WP_Post_Query
来最大化模块化。
结论 (Conclusion)
Criticisms aside, WP_Comment_Query
is a great class for grabbing comments according to your own needs. It makes listing comments a lot easier, especially if you have some custom functionality in there.
除了批评, WP_Comment_Query
是根据您自己的需求获取评论的出色类。 它使列出评论变得容易得多,尤其是当您具有一些自定义功能时。
I strongly recommend familiarizing yourself with the date and meta queries, these are the same in the regular WP_Query
as well so you can re-use your knowledge there.
我强烈建议您熟悉日期和元查询,常规WP_Query
的日期和元查询也是如此,因此您可以在那里重新使用您的知识。
If you have a particularly awesome implementation of your comments that uses WP_Comment_Query
let us know in the comments below!
如果您使用WP_Comment_Query
对注释进行了特别WP_Comment_Query
实现,请在下面的注释中告诉我们!
翻译自: https://scotch.io/tutorials/retrieving-wp_comment_query-in-wordpress