花粉 / query
以流畅的方式创建 WP 查询。
Requires
- laravel/pint: ^1.13
- pollen/wordpress-args: dev-main
Requires (Dev)
- pestphp/pest: ^2.19
README
PostQuery
类是 WordPress 中构建 WP_Query 对象的流畅接口。此类简化了构建复杂查询的过程,并提供了一种更易读和更简洁的方式来定义查询参数。
使用 PostQuery
包装器的优点
当使用 PostQuery
包装器时,您在 WordPress 中查询文章时比使用原始 WP_Query
类获得了几个优势
-
方法链:
PostQuery
包装器允许方法链,这使得以更流畅和易读的方式构建和阅读复杂查询变得更容易。 -
类型安全:
PostQuery
提供了类型提示方法,通过确保查询参数使用正确的数据类型来降低运行时错误的风险。 -
可读性和表达性:
PostQuery
中的方法具有描述性的名称,这使得理解每个查询参数的目的变得更容易。 -
一致性:
PostQuery
强制执行一致的命名约定,并提供了一种标准化的方式来查询文章,从而提高了代码的可维护性。 -
改进的代码结构:使用
PostQuery
促进了更干净、更有组织的代码,将查询逻辑与应用程序的其他部分分离。 -
减少样板代码:包装器简化了常见任务,减少了创建查询所需的样板代码量。
-
IDE 自动完成:与基于数组的参数不同,
PostQuery
包装器在 IDE 中提供自动完成支持,这可以显着提高开发人员的工作效率并减少编码错误。
综合示例
让我们考虑一个例子,其中我们想使用 PostQuery
包装器根据特定标准查询文章,并将其与等效的 WP_Query
代码进行比较。我们将结合使用各种方法来构建一个复杂查询。
使用 PostQuery
包装器
use Pollen\Query\PostQuery; $results = PostQuery::select() ->postType('product') ->taxQuery(function (TaxQuery $query) { $query->where( $query ->taxonomy('category') ->contains(['tee-shirt', 'sportswear']) ->searchByTermSlug() ); }) ->dateQuery(function (DateQuery $query) { $query->where( $query ->date('posted_at') ->between('2021-01-01', '2022-02-01') )->orWhere( $query->date()->created()->after('2021-01-01') ); }) ->metaQuery(function (MetaQuery $query) { $query ->where( $query->meta('status')->equalTo('active') )->orWhere( $query->meta('highlighted')->equalTo(0) ); }) ->userPermission('readable') ->cacheResults() ->get();
等效的 WP_Query
代码
new WP_Query([ 'cache_results' => true, 'date_query' => [ 'relation' => 'OR', [ 'column' => 'posted_at', 'before' => [ 'year' => '2022', 'month' => '02', 'day' => '01', ], 'after' => [ 'year' => '2021', 'month' => '01', 'day' => '01', ], ], [ 'column' => 'post_date', 'after' => [ 'year' => '2021', 'month' => '01', 'day' => '01', ], ], ], 'fields' => 'all', 'meta_query' => [ 'relation' => 'OR', [ 'key' => 'status', 'compare' => '=', 'value' => 'active', ], [ 'key' => 'highlighted', 'compare' => '=', 'type' => 'BINARY', 'value' => 0, ], ], 'perm' => 'readable', 'post_type' => 'product', 'tax_query' => [ 'relation' => 'AND', [ 'taxonomy' => 'category', 'field' => 'slug', 'terms' => [ 'tee-shirt', 'sportswear', ], 'operator' => 'IN', 'include_children' => true, ], ], ]);
我们熟悉的 Wp_Query 表格稍微有点复杂,不是吗? :)
安装
要在您的 WordPress 项目中使用 PostQuery
包装器,您需要使用 Composer 安装 pollen/query
包。
如果您不使用集成了 composer 的 WordPress 环境,您可以按照这篇文章中描述的步骤进行操作。
要安装 Pollen Query,请运行以下命令
composer require pollen/query
Composer 将下载并安装 pollen/query
包及其依赖项。
使用 PostQuery
包装器
一旦您安装了 pollen/query
包并在您的 WordPress 环境中设置了 Composer,您就可以像前几节中描述的那样使用 PostQuery
包装器构建和执行 WordPress 文章查询。
现在,您已经准备好在您的 WordPress 项目中利用 PostQuery
包装器的力量和简单性,以简化您的文章查询并提高代码的可读性和可维护性。
基本用法
要开始使用 PostQuery
类,您可以使用 select()
方法指定要检索的字段,并使用 get()
方法生成具有相应参数的 WP_Query 对象。
默认情况下,PostQuery
类在查询帖子类型方面采用更直观的方法。与 WordPress 的 WP_Query
默认行为不同,如果未指定,则将 post_type
参数设置为 'post'
,PostQuery
类假设更广泛的范围。它默认将 post_type
参数设置为 'all'
,表示它将搜索所有帖子类型。这种默认行为与更合理和包容的方法一致,确保您可以在不需要每次创建查询时都明确指定帖子类型的情况下轻松查询任何类型的帖子。这简化了过程并提高了构建查询时的灵活性。
检索所有字段
PostQuery::select()->get(); // Equivalent to PostQuery::select('*')->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'fields' => 'all', 'post_type' => 'any', ]);
在这种情况下,fields
参数设置为 'all'
,表示应检索所有字段。
指定特定字段
您可以使用带特定字段名的 select()
方法根据您的需求定制查询。
PostQuery::select('id=>parent')->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'fields' => 'id=>parent', 'post_type' => 'all', ]);
在此处,fields
参数设置为 'id=>parent'
,这意味着只检索 'id' 和 'parent' 字段。
仅检索 ID
要仅检索帖子的 ID,可以使用以下代码
PostQuery::select('ids')->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'fields' => 'ids', 'post_type' => 'all', ]);
在这种情况下,fields
参数设置为 'ids'
,表示仅返回帖子 ID。
查找特定帖子 ID
使用 find($postID)
方法创建一个 WP_Query 实例,通过其 ID 检索特定帖子。此方法简化了查询单个帖子的过程,并允许您指定要检索的字段。
要使用 find()
方法,请遵循以下步骤
- 在
PostQuery
类的实例上调用find($postID)
方法,并将所需的帖子 ID 作为参数传递。 - 如果需要,链式调用其他方法进一步自定义查询,例如
fields()
。 - 最后,调用
get()
方法以生成具有指定参数的 WP_Query 对象。
PostQuery::find(1) // you can also pass an array of post ids. ->fields('ids') ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'p' => 1, // Retrieve the post with ID 1 'fields' => 'ids', // Retrieve only the post ID 'post_type' => 'all', ]);
在此示例中,find(1)
方法指定您要检索 ID 为 1 的帖子,fields('ids')
方法表示您只想检索帖子 ID,并将 post_type
参数设置为 'all'
,包括查询中的所有帖子类型。
作者
PostQuery
类提供了几种方法来指定您想要检索的帖子作者。这些方法允许您根据作者 ID、作者用户名和作者 ID(包括或排除)来过滤帖子。
author($authorID)
author($authorID)
方法允许您使用用户 ID 查询特定用户撰写的帖子。以下是一个示例
PostQuery::select() ->author(1) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'author' => 1, // Retrieve posts authored by the user with ID 1 'post_type' => 'all' // Include all post types in the query ]);
authorName($authorUsername)
authorName($authorUsername)
方法允许您使用用户名查询特定用户撰写的帖子。以下是一个示例
PostQuery::select() ->authorName('taylor') ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'author_name' => 'taylor', // Retrieve posts authored by the user with the username 'taylor' 'post_type' => 'all' // Include all post types in the query ]);
authorIn($authorIDs)
authorIn($authorIDs)
方法允许您查询由一个或多个用户(通过用户 ID 指定)撰写的帖子。您可以向此方法传递用户 ID 数组。以下是一个示例
PostQuery::select() ->authorIn([1, 2, 3]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'author__in' => [1, 2, 3], // Retrieve posts authored by users with IDs 1, 2, or 3 'post_type' => 'all' // Include all post types in the query ]);
authorNotIn($authorIDs)
authorNotIn($authorIDs)
方法允许您排除由一个或多个用户(通过用户 ID 指定)撰写的帖子。您可以向此方法传递用户 ID 数组。以下是一个示例
PostQuery::select() ->authorNotIn([1, 2, 3]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'author__not_in' => [1, 2, 3], // Exclude posts authored by users with IDs 1, 2, or 3 'post_type' => 'all' // Include all post types in the query ]);
类别
PostQuery
类允许您根据类别使用各种方法查询帖子。这些方法使您能够根据类别 ID、类别名称以及包括或排除类别来过滤帖子。
cat($categoryID)
cat($categoryID)
方法允许您通过指定其类别 ID 来查询属于特定类别的帖子。以下是一个示例
PostQuery::select() ->cat(1) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'cat' => 1, // Retrieve posts from category with ID 1 'post_type' => 'all', // Include all post types in the query ]);
categoryName($categoryName)
《categoryName($categoryName)》方法允许您通过指定其名称来查询属于特定类别的帖子。以下是一个示例:
PostQuery::select() ->categoryName('sales') ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'category_name' => 'sales', // Retrieve posts from the 'sales' category 'post_type' => 'all', // Include all post types in the query ]);
categoryIn($categoryIDs)
《categoryIn($categoryIDs)》方法允许您通过指定其类别ID来包含一个或多个类别的帖子。您可以将一个类别ID数组传递给此方法。以下是一个示例:
PostQuery::select() ->categoryIn([1, 2, 3]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'category__in' => [1, 2, 3], // Include posts from categories with IDs 1, 2, or 3 'post_type' => 'all', // Include all post types in the query ]);
categoryNotIn($categoryIDs)
《categoryNotIn($categoryIDs)》方法允许您通过指定其类别ID来排除一个或多个类别的帖子。您可以将一个类别ID数组传递给此方法。以下是一个示例:
PostQuery::select() ->categoryNotIn([1, 2, 3]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'category__not_in' => [1, 2, 3], // Exclude posts from categories with IDs 1, 2, or 3 'post_type' => 'all', // Include all post types in the query ]);
标签
《PostQuery》类允许您使用各种方法通过标签查询帖子。这些方法使您能够根据标签名称、标签ID、标签别名以及包含或排除标签来过滤帖子。
tag($tagName)
《tag($tagName)》方法允许您通过指定其名称来查询与特定标签关联的帖子。以下是一个示例:
PostQuery::select() ->tag('programming') ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag' => 'programming', // Retrieve posts associated with the 'programming' tag 'post_type' => 'all', // Include all post types in the query ]);
tagId($tagID)
《tagId($tagID)》方法允许您通过指定其ID来查询与特定标签关联的帖子。以下是一个示例:
PostQuery::select() ->tagId(1) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag_id' => 1, // Retrieve posts associated with the tag with ID 1 'post_type' => 'all', // Include all post types in the query ]);
tagAnd($tagIDs)
《tagAnd($tagIDs)》方法允许您通过指定其ID来查询与所有指定的标签关联的帖子。您可以将一个标签ID数组传递给此方法。以下是一个示例:
PostQuery::select() ->tagAnd([1, 2]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag__and' => [1, 2], // Retrieve posts associated with both tags with IDs 1 and 2 'post_type' => 'all', // Include all post types in the query ]);
tagIn($tagIDs)
《tagIn($tagIDs)》方法允许您通过指定其ID来查询与一个或多个标签关联的帖子。您可以将一个标签ID数组传递给此方法。以下是一个示例:
PostQuery::select() ->tagIn([3, 4]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag__in' => [3, 4], // Retrieve posts associated with tags with IDs 3 or 4 'post_type' => 'all', // Include all post types in the query ]);
tagNotIn($tagIDs)
《tagNotIn($tagIDs)》方法允许您通过指定其ID来排除与一个或多个标签关联的帖子。您可以将一个标签ID数组传递给此方法。以下是一个示例:
PostQuery::select() ->tagNotIn([5, 6]) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag__not_in' => [5, 6], // Exclude posts associated with tags with IDs 5 or 6 'post_type' => 'all', // Include all post types in the query ]);
tagSlugAnd($tagSlugs)
《tagSlugAnd($tagSlugs)》方法允许您通过指定其别名来查询与所有指定的标签关联的帖子。您可以将一个标签别名数组传递给此方法。以下是一个示例:
PostQuery::select() ->tagSlugAnd(['dev', 'qa']) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag_slug__and' => ['dev', 'qa'], // Retrieve posts associated with both 'dev' and 'qa' tags 'post_type' => 'all', // Include all post types in the query ]);
tagSlugIn($tagSlugs)
《tagSlugIn($tagSlugs)》方法允许您通过指定其别名来查询与一个或多个标签关联的帖子。您可以将一个标签别名数组传递给此方法。以下是一个示例:
PostQuery::select() ->tagSlugIn(['frontend', 'backend']) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'tag_slug__in' => ['frontend', 'backend'], // Retrieve posts associated with 'frontend' or 'backend' tags 'post_type' => 'all', // Include all post types in the query ]);
分类查询
《PostQuery》类允许您使用《taxQuery()`》方法根据分类术语过滤帖子。此方法提供了一种构建涉及分类术语及其关系复杂查询的强大方式。
简单的分类查询
在其最简单的形式中,您可以使用《taxQuery()`》方法通过单个分类和术语列表来过滤帖子。例如
PostQuery::select() ->taxQuery(function (TaxQuery $query) { $query->where( $query ->taxonomy('category') ->contains(['tee-shirt', 'sportswear']) ->searchByTermSlug() ); }) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'post_type' => 'all', 'tax_query' => [ 'relation' => 'AND', [ 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['tee-shirt', 'sportswear'], 'operator' => 'IN', 'include_children' => true, ], ], ]);
“或”关系
您还可以使用“或”关系来查询符合任何指定分类条件的帖子。例如
PostQuery::select() ->taxQuery(function (TaxQuery $query) { $query->where( $query ->taxonomy('category') ->contains([10, 20]) ->searchById() )->orWhere( $query ->taxonomy('event') ->contains(['black-friday', 'christmas-sales']) ->searchByTermSlug() ); }) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'post_type' => 'all', 'tax_query' => [ 'relation' => 'OR', [ 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => [10, 20], 'operator' => 'IN', 'include_children' => true, ], [ 'taxonomy' => 'event', 'field' => 'slug', 'terms' => ['black-friday', 'christmas-sales'], 'operator' => 'IN', 'include_children' => true, ], ], ]);
嵌套条件
您还可以在《Tax_Query》中创建嵌套条件。在以下示例中,我们使用了带有“或”和“与”关系的嵌套条件
PostQuery::select() ->taxQuery(function (TaxQuery $query) { $query ->where( $query->taxonomy('status')->notContains(['private']) ) ->orWhere(function (TaxQuery $query) { $query ->where( $query->taxonomy('attributes')->exists() ) ->orWhere( $query->taxonomy('product_cat')->contains(['tee-shirt', 'sportswear']) ); }) ->orWhere(function (TaxQuery $query) { $query ->where( $query->taxonomy('promo_cat')->contains(['summer', 'blackfriday']) ) ->andWhere( $query->taxonomy('new_products')->notExists() ); }); }) ->get();
这将生成以下 WP_Query 参数
new WP_Query([ 'post_type' => 'all', 'tax_query' => [ 'relation' => 'OR', [ 'taxonomy' => 'status', 'field' => 'term_id', 'terms' => [ 'private', ], 'operator' => 'NOT IN', 'include_children' => true, ], [ 'relation' => 'OR', [ 'taxonomy' => 'attributes', 'field' => 'term_id', 'terms' => null, 'operator' => 'EXISTS', 'include_children' => true, ], [ 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => [ 'tee-shirt', 'sportswear', ], 'operator' => 'IN', 'include_children' => true, ], ], [ 'relation' => 'AND', [ 'taxonomy' => 'promo_cat', 'field' => 'term_id', 'terms' => [ 'summer', 'blackfriday', ], 'operator' => 'IN', 'include_children' => true, ], [ 'taxonomy' => 'new_products', 'field' => 'term_id', 'terms' => null, 'operator' => 'NOT EXISTS', 'include_children' => true, ], ], ], ])
搜索
《PostQuery》类允许您使用《search()`》方法在帖子上进行基于关键字的搜索。此方法帮助您过滤与特定关键字或短语匹配的帖子。
search($keyword)
《search($keyword)》方法允许您对帖子执行基于关键字的搜索。您可以将所需的关键字或短语作为参数指定。以下是一个示例:
PostQuery::select() ->search('my keyword') ->get();
这生成以下WP_Query参数:
new WP_Query([ 's' => 'my keyword', // Perform a keyword-based search for posts containing 'my keyword' 'post_type' => 'all', ]);
文章
《PostQuery》类提供用于根据各种与帖子相关的参数过滤帖子的方法。这些方法允许您指定要查询的帖子类型、帖子ID、帖子别名、帖子父级等。
postType($type)
《postType($type)》方法允许您指定要查询的帖子类型。您可以将帖子类型作为参数提供。以下是一个示例:
PostQuery::select() ->postType('article') ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_type' => 'article', // Retrieve posts of the 'article' post type ]);
postId($id)
《postId($id)》方法允许您通过ID查询特定的文章。您可以提供文章ID作为参数。例如
PostQuery::select() ->postId(42) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'p' => 42, // Retrieve the post with ID 42 'post_type' => 'all' ]);
postSlug($slug)
《postSlug($slug)》方法允许您通过slug查询特定的文章。您可以提供文章slug作为参数。例如
PostQuery::select() ->postSlug('mon-article') ->get();
这生成以下WP_Query参数:
new WP_Query([ 'name' => 'mon-article', // Retrieve the post with the slug 'mon-article' 'post_type' => 'all' ]);
postParent($parentID)
《postParent($parentID)》方法允许您查询具有特定父文章的文章。您可以提供父文章ID作为参数。例如
PostQuery::select() ->postParent(5) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_parent' => 5, // Retrieve posts with a parent post of ID 5 'post_type' => 'all', ]);
whereParentIn($parentIDs)
《whereParentIn($parentIDs)》方法允许您查询具有由其ID指定的父文章的文章。您可以将父文章ID数组传递给此方法。例如
PostQuery::select() ->whereParentIn([1, 2, 3]) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_parent__in' => [1, 2, 3], // Retrieve posts with parent post IDs in the array 'post_type' => 'all' ]);
whereParentNotIn($parentIDs)
《whereParentNotIn($parentIDs)》方法允许您排除具有由其ID指定的父文章的文章。您可以将父文章ID数组传递给此方法。例如
PostQuery::select() ->whereParentNotIn([4, 5, 6]) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_parent__not_in' => [4, 5, 6], // Exclude posts with parent post IDs in the array 'post_type' => 'all' ]);
whereIn($postIDs)
《whereIn($postIDs)》方法允许您查询具有特定ID的文章。您可以将文章ID数组传递给此方法。例如
PostQuery::select() ->whereIn([7, 8, 9]) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post__in' => [7, 8, 9], // Retrieve posts with IDs in the array 'post_type' => 'all' ]);
whereNotIn($postIDs)
《whereNotIn($postIDs)》方法允许您排除具有特定ID的文章。您可以将文章ID数组传递给此方法。例如
PostQuery::select() ->whereNotIn([10, 11, 12]) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post__not_in' => [10, 11, 12], // Exclude posts with IDs in the array 'post_type' => 'all' ]);
slugIn($slugs)
《slugIn($slugs)》方法允许您查询具有特定slug的文章。您可以将文章slug数组传递给此方法。例如
PostQuery::select() ->slugIn(['slug-1', 'slug-2']) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_name__in' => ['slug-1', 'slug-2'], // Retrieve posts with slugs in the array 'post_type' => 'all' ]);
注意:'pagename'和'page_id'
与WP_Query不同,《PostQuery》类不提供针对'pagename'和'page_id'参数的单独方法。相反,在指定'post_type'为'page'时,您可以使用'name'和'p'参数来实现等效的结果
PostQuery::select() ->postType('page') ->postSlug('my-page') ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_type' => 'page', // Query for pages 'name' => 'my-page', // Specify the page slug 'post_type' => 'all' ]);
密码
《PostQuery》类提供方法以根据其密码保护状态和特定文章密码过滤文章。
withPassword()
《withPassword()`方法允许您查询已设置密码保护的文章。您可以使用此方法检索需要密码才能访问的文章。例如
PostQuery::select() ->withPassword() ->get();
这生成以下WP_Query参数:
new WP_Query([ 'has_password' => true, // Retrieve posts with password protection 'post_type' => 'all' ]);
withoutPassword()
《withoutPassword()`方法允许您查询未设置密码保护的文章。您可以使用此方法排除需要密码才能访问的文章。例如
PostQuery::select() ->withoutPassword() ->get();
这生成以下WP_Query参数:
new WP_Query([ 'has_password' => false, // Exclude posts with password protection 'post_type' => 'all' ]);
withPassword($password)
《withPassword($password)》方法允许您查询已设置特定文章密码的文章。您可以将所需的文章密码作为参数提供。例如
PostQuery::select() ->withPassword('zxcvbn') ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_password' => 'zxcvbn', // Retrieve posts with the specified post password 'post_type' => 'all' ]);
状态
《PostQuery》类允许您使用《postStatus()`方法根据文章的状态过滤文章。此方法有助于您查询具有特定状态的文章。
postStatus($status)
《postStatus($status)》方法允许您指定要检索的文章的状态。您可以将所需的状态作为参数提供。例如
PostQuery::select() ->postStatus('publish') ->get();
这生成以下WP_Query参数:
new WP_Query([ 'post_status' => 'publish', // Retrieve posts with the 'publish' status 'post_type' => 'all' ]);
您可以使用此方法查询具有不同状态的文章,例如'publish'、'draft'、'pending'或您在WordPress安装中定义的自定义状态。它为您查询中检索到的文章的状态提供精确控制。
评论参数
《PostQuery》类提供《commentCount()`方法以根据文章的评论数量过滤文章。此方法允许您检索具有特定数量的评论的文章。
commentCount($count)
《commentCount($count)》方法允许您指定文章应具有多少评论才能在查询中被检索。您可以将所需的评论数作为参数提供。例如
PostQuery::select() ->commentCount(1) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'comment_count' => 1, // Retrieve posts with exactly 1 comment ]);
分页
《PostQuery》类提供方法来控制查询结果分页。这些方法允许您指定每页检索的文章数量、跳过一定数量的文章等。
take($count), limit($count) 或 postsPerPage($count)
take($count)
、limit($count)
和 postsPerPage($count)
方法允许您指定每页要检索的帖子数量。您可以提供一个所需的帖子计数参数。例如
PostQuery::select() ->take(5) ->get();
这些方法生成以下 WP_Query 参数
new WP_Query([ 'posts_per_page' => 5, // Retrieve 5 posts per page ]);
您可以使用这些方法来控制查询结果每页显示的帖子数量。
skip($count) 或 offset($count)
skip($count)
和 offset($count)
方法允许您在查询结果中跳过一定数量的帖子。您可以提供一个所需的跳过计数参数。例如
PostQuery::select() ->skip(5) ->get();
这些方法生成以下 WP_Query 参数
new WP_Query([ 'offset' => 5, // Skip the first 5 posts in the query results ]);
您可以使用这些方法来跳过特定数量的帖子,这在创建分页查询时很有用。
noPaging()
noPaging()
方法允许您完全禁用分页,检索所有符合查询条件的帖子而不进行分页。例如
PostQuery::select() ->noPaging() ->get();
这生成以下WP_Query参数:
new WP_Query([ 'nopaging' => true, // Retrieve all posts without pagination ]);
当您想在一个查询中检索所有匹配的帖子时,请使用此方法,无论数量多少。
postsPerArchivePage($count)
postsPerArchivePage($count)
方法允许您指定每个存档页面显示的帖子数量。这对于分类或标签存档等存档页面特别有用。例如
PostQuery::select() ->postsPerArchivePage(5) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'posts_per_archive_page' => 5, // Display 5 posts per archive page ]);
您可以使用此方法来控制存档页面上显示的帖子数量。
page($pageNumber)
page($pageNumber)
方法允许您在分页查询结果时指定页面编号。您可以提供一个所需的页面编号参数。例如
PostQuery::select() ->page(666) ->get();
这生成以下WP_Query参数:
new WP_Query([ 'page' => 666, // Retrieve results for page number 666 ]);
当您想在一个分页查询中检索特定的结果页面时,请使用此方法。
ignoreStickyPosts()
ignoreStickyPosts()
方法允许您从查询结果中排除置顶帖子。置顶帖子是指固定在列表顶部的帖子。例如
PostQuery::select() ->ignoreStickyPosts() ->get();
这生成以下WP_Query参数:
new WP_Query([ 'ignore_sticky_posts' => true, // Exclude sticky posts from the query ]);
排序
PostQuery
类提供了控制检索帖子顺序的方法。您可以指定一个或多个orderby参数,根据各种标准对查询结果进行排序。
orderBy($field, $order = 'DESC')
orderBy($field, $order = 'DESC')
方法允许您指定按哪个字段排序帖子以及排序的顺序。您可以提供所需的字段和顺序作为参数。例如
PostQuery::select() ->orderBy('most_comments') ->orderBy('post_date', 'ASC') ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'orderby' => [ 'most_comments' => 'DESC', // Order by 'most_comments' in descending order 'post_date' => 'ASC', // Then order by 'post_date' in ascending order ], ]);
日期
PostQuery
类允许您使用 DateQuery
类根据日期相关标准查询帖子。此类提供了创建复杂日期查询的方法,允许您通过发布、修改或自定义日期过滤帖子。
dateQuery($callback)
dateQuery($callback)
方法允许您使用 DateQuery
类定义一个复杂的日期查询。您可以传递一个回调函数来创建日期查询条件。例如
PostQuery::select()->dateQuery(function (DateQuery $query) { $query ->where( $query->date('edited_at')->before('2022-01-01')->after([ 'year' => '2021', 'month' => '01', 'day' => '01', ]) ) ->inclusive(); })->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'date_query' => [ 'relation' => 'AND', [ 'column' => 'edited_at', 'before' => [ 'year' => 2022, 'month' => 1, 'day' => 1, 'hour' => 12, 'minute' => 0, 'second' => 0, ], 'after' => [ 'year' => 2021, 'month' => 1, 'day' => 1, ], ], 'inclusive' => true, ], ]);
您可以使用此方法创建包含“之前”、“之后”和包含/排除设置的复杂日期查询。
date($column = 'post_date')
在 DateQuery
类中,date($column = 'post_date')
方法允许您指定要查询的列或日期类型。您可以选择 'post_date'、'post_modified' 或其他自定义日期列。例如
$query->date('edited_at');
before($date)
在 DateQuery
类中,before($date)
方法允许您指定日期应在某个时间点之前。您可以提供各种格式的日期,例如 'YYYY-MM-DD' 或指定 'year'、'month'、'day'、'hour'、'minute' 和 'second' 的数组。
after($date)
在 DateQuery
类中,after($date)
方法允许您指定日期应在某个时间点之后。与 before()
方法类似,您可以提供各种格式的日期。
between($start, $end)
DateQuery
类中的 between($start, $end)
方法允许您指定日期应在两个时间点之间。您可以使用各种格式提供起始和结束日期。
created()
DateQuery
类中的 modified()
方法允许您指定日期查询应用于帖子的最后修改日期,而不是默认的 'post_date' 列。这对于区分帖子的创建和修改日期非常有用。
inclusive()
DateQuery
类中的 inclusive()
方法允许您指定日期查询应包括与指定的确切日期和时间匹配的帖子。这在使用 before()
和 after()
方法时特别有用。
元查询
PostQuery
类允许您使用 MetaQuery
类执行基于帖子元数据的自定义查询。此类提供了创建复杂元查询的方法,允许您根据自定义字段值过滤帖子。
metaQuery($callback)
metaQuery($callback)
方法允许您使用 MetaQuery
类定义复杂的元查询。您可以通过传递回调函数来创建元查询条件。例如
PostQuery::select()->metaQuery(function (MetaQuery $query) { $query->where( $query->meta('status')->equalTo('active') ); })->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'meta_query' => [ 'relation' => 'AND', [ 'key' => 'status', 'compare' => '=', 'type' => 'CHAR', 'value' => 'active', ], ], ]);
meta($key)
MetaQuery
类中的 meta($key)
方法允许您指定要查询的自定义字段键。例如
比较方法
MetaQuery
类提供了一些方法来指定对自定义字段执行的比较操作。您可以链接这些方法来构建复杂条件。
ofType($type)
此方法允许您指定要使用的比较类型。可能的类型是类常量,例如 MetaQueryBuilder::NUMERIC
、MetaQueryBuilder::CHAR
、MetaQueryBuilder::DATE
等。默认情况下,类型将根据比较期间提供的值自动确定。
使用示例
$query->meta('my_post_meta')->ofType('numeric'); // You can also use a number
注意
detectValueType
方法用于内部自动确定比较期间提供的值的数据类型。当您使用其他比较方法时,它将自动调用。
此方法执行以下检查以确定数据类型
- 如果值是数组,则采用第一个元素的数据类型。
- 如果使用
ofType
方法显式设置数据类型,则使用该数据类型。 - 如果值是
null
,则默认为CHAR
数据类型。 - 如果值是
0
或1
,则使用BINARY
数据类型。 - 如果值是负整数,则使用
SIGNED
数据类型。 - 如果值是非负整数,则使用
UNSIGNED
数据类型。 - 如果值是浮点数,则使用
DECIMAL
数据类型。 - 如果值是只包含数字日期的字符串(例如,'2022-01-01'),则使用
DATE
数据类型。 - 如果值是只包含数字时间的字符串(例如,'12:00:00'),则使用
TIME
数据类型。 - 如果值是包含日期和时间的字符串(例如,'2022-01-01 12:00:00'),则使用
DATETIME
数据类型。 - 如果上述任何条件都不适用,则默认为
CHAR
数据类型。
equalTo($value)
此方法指定自定义字段必须等于某个特定值。
使用示例
$query->meta('my_post_meta')->equalTo('active'); // You can also use a number
notEqualTo(mixed $value)
此方法指定自定义字段必须不等于某个特定值。
使用示例
$query->meta('my_post_meta')->notEqualTo('inactive');
greaterThan($value)
此方法指定自定义字段必须大于某个特定值。
使用示例
$query->meta('my_post_meta')->greaterThan(100);
greaterOrEqualTo($value)
此方法指定自定义字段必须大于或等于某个特定值。
使用示例
$query->meta('my_post_meta')->greaterOrEqualTo(100);
lessThan($value)
此方法指定自定义字段必须小于某个特定值。
使用示例
$query->meta('my_post_meta')->lessThan(5);
lessOrEqualTo($value)
此方法指定自定义字段必须小于或等于某个特定值。
使用示例
$query->meta('my_post_meta')->lessOrEqualTo(5);
between(mixed $lowerBoundary, mixed $upperBoundary): self
此方法指定自定义字段必须在两个给定值之间。
使用示例
$query->meta('my_post_meta')->between('2022-01-01', '2022-12-31');
notBetween($lowerBoundary, $upperBoundary)
此方法指定自定义字段不得在两个给定值之间。
使用示例
$query->meta('my_post_meta')->notBetween('2022-01-01', '2022-12-31');
like(string $value): self
此方法指定自定义字段与字符串的局部匹配。
使用示例
$query->meta('my_post_meta')->like('keyword');
notLike($value)
此方法指定自定义字段不得与字符串部分匹配。
使用示例
$query->meta('my_post_meta')->notLike('excluded');
in($values)
此方法指定自定义字段必须匹配给定数组中的一个值。
使用示例
$query->meta('my_post_meta')->in(['value1', 'value2', 'value3']);
notIn($values)
此方法指定自定义字段不得匹配给定数组中的任何值。
使用示例
$query->meta('my_post_meta')->notIn(['excluded1', 'excluded2']);
state($value)
在MetaQuery
类中的state($value)
方法允许您使用命名元查询,并使用此状态进行排序。有关更多信息,请参阅此部分文档。
使用示例
PostQuery::select() ->metaQuery(function (MetaQuery $query) { $query ->where( $query ->meta('menu_order') ->state('menu_order_state') ->greaterThan(10) ); }) ->orderBy('menu_order_state', 'ASC') ->get();
exists()
此方法指定自定义字段必须存在(已定义)。
使用示例
$query->meta('my_post_meta')->exists();
notExists()
此方法指定自定义字段不得存在(未定义)。
使用示例
$query->meta('my_post_meta')->notExists();
metaQuery
方法链
您可以将多个meta()
方法链起来以创建复杂的元查询。例如
PostQuery::select()->metaQuery(function (MetaQuery $query) { $query ->where( $query->meta('status')->equalTo('active') ) ->orWhere( $query->meta('highlighted')->equalTo(1) ); })->get();
这会在两个条件之间生成一个具有'OR'关系的元查询。
嵌套元查询
您可以通过在metaQuery()
回调中使用MetaQuery
类来创建嵌套元查询。这允许您创建具有多级条件的复杂元查询。例如
PostQuery::select() ->metaQuery(function (MetaQuery $query) { $query ->where( $query->meta('status')->equalTo('active') ) ->orWhere(function (MetaQuery $query) { $query ->where( $query->meta('_sku')->equalTo('H123456789') ) ->orWhere( $query->meta('_sku')->equalTo('D123456784') ); }) ->orWhere(function (MetaQuery $query) { $query ->where( $query->meta('promo_cat')->notIn(['summer', 'blackfriday'])->state('promo_cat') ) ->andWhere( $query->meta('promo_cat')->notEqualTo('sales') ); }) ->orWhere( $query->meta('sale_date') ->between('2024-01-01', '2024-12-31') ); }) ->orderBy('promo_cat') ->get();
权限
PostQuery
类允许您根据特定用户权限查询帖子。您可以使用以下权限参数根据用户的访问权限过滤帖子。
userPermission(string $permission)
userPermission
方法用于根据用户权限过滤帖子。它接受一个参数
-
$permission
(字符串):指定要过滤帖子的权限类型。有效值包括'readable'
:此权限过滤用户可以读取的帖子。'editable'
:此权限过滤用户可以编辑的帖子。
过滤用户可以读取的帖子。
PostQuery::select() ->userPermission('readable') ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'perm' => 'readable', 'post_type' => 'all', ]);
过滤用户可以编辑的帖子。
PostQuery::select() ->userPermission('editable') ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'perm' => 'editable', 'post_type' => 'all', ]);
无效权限
PostQuery::select() ->userPermission('invalid') ->get();
当提供无效权限时,生成的WP_Query将返回所有帖子。
new WP_Query([ 'post_type' => 'all', ]);
MIME 类型
PostQuery
类允许您根据帖子的MIME类型过滤帖子。您可以使用postMimeType
方法指定您想要过滤的MIME类型。
postMimeType(string|array $mimeTypes)
postMimeType
方法根据MIME类型过滤帖子。它接受一个参数
$mimeTypes
(字符串或数组):指定要过滤帖子的MIME类型。您可以提供一个字符串作为单个MIME类型或多个MIME类型的数组。
根据单个MIME类型过滤帖子(例如,'image/gif')。
PostQuery::select() ->postMimeType('image/gif') ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'post_mime_type' => 'image/gif', 'post_type' => 'all', ]);
根据MIME类型的数组过滤帖子。
PostQuery::select() ->postMimeType(['image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon']) ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'post_mime_type' => ['image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon'], 'post_type' => 'all', ]);
缓存
PostQuery
类提供方法用于在查询帖子时控制缓存行为。
cacheResults()
cacheResults
方法启用查询结果的缓存。当您使用此方法时,查询结果将被缓存以实现更快的检索。它不接受任何参数。
PostQuery::select() ->cacheResults() ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'cache_results' => true, 'post_type' => 'all', ]);
updateMetaCache($update)
updateMetaCache
方法允许您控制帖子元数据是否缓存。您可以使用此方法指定是否更新帖子元数据缓存或禁用它。
$update
(布尔值):传递true
以更新帖子元数据缓存或false
以禁用它。
PostQuery::select() ->updateMetaCache(false) ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'update_post_meta_cache' => false, 'post_type' => 'all', ]);
updateTermCache($update)
updateTermCache
方法允许您控制帖子术语数据是否缓存。您可以使用此方法指定是否更新帖子术语缓存或禁用它。
$update
(布尔值):传递true
以更新帖子术语缓存或false
以禁用它。
PostQuery::select() ->updateTermCache(true) ->get();
此方法生成以下 WP_Query 参数
new WP_Query([ 'update_post_term_cache' => true, 'post_type' => 'all', ]);