Download the PHP package pollen/query without Composer
On this page you can find all versions of the php package pollen/query. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Package query
Short Description Create WP Query in a fluent way.
License GPL-2.0-or-later
Informations about the package query
PostQuery Class
The PostQuery
class is a fluent interface for constructing WP_Query objects in WordPress. This class simplifies the process of building complex queries and provides a more readable and concise way to define query parameters.
- Advantages
- Installation
- Basic Usage
- Author
- Category
- Tag
- Tax_Query
- Search
- Post
- Password
- Status
- Comment Parameter
- Pagination
- Order
- Date
- Meta Query
- Permission
- Mimetype
- Cache
Advantages of Using PostQuery
Wrapper
When using the PostQuery
wrapper, you gain several advantages over using the original WP_Query
class for querying posts in WordPress:
-
Method Chaining: The
PostQuery
wrapper allows for method chaining, making it easier to construct and read complex queries in a more fluent and readable manner. -
Type Safety:
PostQuery
provides type-hinted methods, reducing the risk of runtime errors by ensuring that the correct data types are used for query parameters. -
Readable and Expressive: The methods in
PostQuery
have descriptive names, making it easier to understand the purpose of each query parameter. -
Consistency:
PostQuery
enforces consistent naming conventions and provides a standardized way to query posts, enhancing code maintainability. -
Improved Code Structure: Using
PostQuery
promotes cleaner and more organized code, separating query logic from the rest of your application. -
Reduced Boilerplate: The wrapper simplifies common tasks, reducing the amount of boilerplate code needed to create queries.
- IDE Autocompletion: Unlike array-based arguments, the
PostQuery
wrapper provides autocompletion support in IDEs, which can significantly improve developer productivity and reduce coding errors.
Comprehensive Example
Let's consider an example where we want to query posts with specific criteria using the PostQuery
wrapper and compare it to the equivalent WP_Query
code. We'll combine various methods to construct a complex query.
Using PostQuery
Wrapper
Equivalent WP_Query
Code
The table of our good old Wp_Query is a little complex, isn't it? :)
Installation
To use the PostQuery
wrapper in your WordPress project, you need to install the pollora/query
package using Composer.
If you're not using a WordPress environment that integrate composer, you can follow the steps described in this article.
To install Pollora Query, run the following command :
Composer will download and install the pollora/query
package and its dependencies.
Using the PostQuery
Wrapper
Once you've installed the pollora/query
package and set up Composer in your WordPress environment, you can use the PostQuery
wrapper to construct and execute WordPress post queries as described in the previous sections.
Now, you're ready to harness the power and simplicity of the PostQuery
wrapper in your WordPress project to streamline your post queries and improve code readability and maintainability.
Basic Usage
To get started with the PostQuery
class, you can use the select()
method to specify the fields you want to retrieve and the get()
method to generate a WP_Query object with the corresponding arguments.
By default, the PostQuery
class adopts a more intuitive approach when it comes to querying posts by post type. Unlike the default behavior of WordPress's WP_Query
, which sets the post_type
parameter to 'post'
if not specified, the PostQuery
class assumes a broader scope. It sets the post_type
parameter to 'all'
by default, indicating that it will search across all post types. This default behavior aligns with a more logical and inclusive approach, ensuring that you can effortlessly query posts of any type without needing to explicitly specify the post type every time you create a query. This simplifies the process and enhances flexibility when constructing your queries.
Retrieve All Fields
This will generate the following WP_Query arguments:
In this case, the fields
argument is set to 'all'
, indicating that all fields should be retrieved.
Specify Specific Fields
You can use the select()
method with specific field names to tailor your query to your needs.
This will generate the following WP_Query arguments:
Here, the fields
argument is set to 'id=>parent'
, which means only the 'id' and 'parent' fields will be retrieved.
Retrieve Only IDs
To retrieve only the IDs of the posts, you can use the following code:
This will generate the following WP_Query arguments:
In this case, the fields
argument is set to 'ids'
, indicating that only the post IDs will be returned.
Find specific post id
The find($postID)
method is used to create a WP_Query instance that retrieves a specific post by its ID. This method simplifies the process of querying a single post and allows you to specify the fields you want to retrieve.
To use the find()
method, follow these steps:
- Call the
find($postID)
method on an instance of thePostQuery
class, passing the desired post ID as a parameter. - Chain other methods to further customize the query, such as
fields()
, if needed. - Finally, call the
get()
method to generate a WP_Query object with the specified arguments.
This will generate the following WP_Query arguments:
In this example, the find(1)
method specifies that you want to retrieve the post with ID 1, the fields('ids')
method indicates that you only want to retrieve the post ID, and the post_type
argument is set to 'all'
, including all post types in the query.
Author
The PostQuery
class provides several methods for specifying the author(s) of the posts you want to retrieve. These methods allow you to filter posts based on author IDs, author usernames, and author IDs to include or exclude.
author($authorID)
The author($authorID)
method allows you to query posts authored by a specific user using their user ID. Here's an example:
This will generate the following WP_Query arguments:
authorName($authorUsername)
The authorName($authorUsername)
method allows you to query posts authored by a specific user using their username. Here's an example:
This will generate the following WP_Query arguments:
authorIn($authorIDs)
The authorIn($authorIDs)
method allows you to query posts authored by one or more users specified by their user IDs. You can pass an array of user IDs to this method. Here's an example:
This will generate the following WP_Query arguments:
authorNotIn($authorIDs)
The authorNotIn($authorIDs)
method allows you to exclude posts authored by one or more users specified by their user IDs. You can pass an array of user IDs to this method. Here's an example:
This will generate the following WP_Query arguments:
Category
The PostQuery
class allows you to query posts based on categories using various methods. These methods enable you to filter posts by category ID, category name, and include or exclude categories.
cat($categoryID)
The cat($categoryID)
method allows you to query posts belonging to a specific category by specifying its category ID. Here's an example:
This generates the following WP_Query arguments:
categoryName($categoryName)
The categoryName($categoryName)
method allows you to query posts belonging to a specific category by specifying its name. Here's an example:
This generates the following WP_Query arguments:
categoryIn($categoryIDs)
The categoryIn($categoryIDs)
method allows you to include posts from one or more categories specified by their category IDs. You can pass an array of category IDs to this method. Here's an example:
This generates the following WP_Query arguments:
categoryNotIn($categoryIDs)
The categoryNotIn($categoryIDs)
method allows you to exclude posts from one or more categories specified by their category IDs. You can pass an array of category IDs to this method. Here's an example:
This generates the following WP_Query arguments:
Tag
The PostQuery
class allows you to query posts based on tags using various methods. These methods enable you to filter posts by tag name, tag ID, tag slugs, and include or exclude tags.
tag($tagName)
The tag($tagName)
method allows you to query posts associated with a specific tag by specifying its name. Here's an example:
This generates the following WP_Query arguments:
tagId($tagID)
The tagId($tagID)
method allows you to query posts associated with a specific tag by specifying its ID. Here's an example:
This generates the following WP_Query arguments:
tagAnd($tagIDs)
The tagAnd($tagIDs)
method allows you to query posts that are associated with all of the specified tags by specifying their IDs. You can pass an array of tag IDs to this method. Here's an example:
This generates the following WP_Query arguments:
tagIn($tagIDs)
The tagIn($tagIDs)
method allows you to query posts associated with one or more tags by specifying their IDs. You can pass an array of tag IDs to this method. Here's an example:
This generates the following WP_Query arguments:
tagNotIn($tagIDs)
The tagNotIn($tagIDs)
method allows you to exclude posts associated with one or more tags by specifying their IDs. You can pass an array of tag IDs to this method. Here's an example:
This generates the following WP_Query arguments:
tagSlugAnd($tagSlugs)
The tagSlugAnd($tagSlugs)
method allows you to query posts that are associated with all of the specified tags by specifying their slugs. You can pass an array of tag slugs to this method. Here's an example:
This generates the following WP_Query arguments:
tagSlugIn($tagSlugs)
The tagSlugIn($tagSlugs)
method allows you to query posts associated with one or more tags by specifying their slugs. You can pass an array of tag slugs to this method. Here's an example:
This generates the following WP_Query arguments:
Tax_Query
The PostQuery
class allows you to filter posts based on taxonomy terms using the taxQuery()
method. This method provides a powerful way to construct complex queries involving taxonomy terms and their relationships.
Simple tax query
In its simplest form, you can use the taxQuery()
method to filter posts by a single taxonomy and a list of terms. For example:
This generates the following WP_Query arguments:
'OR' Relation
You can also use the 'OR' relation to query posts that match any of the specified taxonomy conditions. For example:
This generates the following WP_Query arguments:
Nested Conditions
You can also create nested conditions within the Tax_Query. In the following example, we use nested conditions with 'OR' and 'AND' relations:
This generates the following WP_Query arguments:
Search
The PostQuery
class allows you to perform keyword-based searches on posts using the search()
method. This method helps you filter posts that match a specific keyword or phrase.
search($keyword)
The search($keyword)
method allows you to perform a keyword-based search for posts. You can specify the desired keyword or phrase as a parameter. Here's an example:
This generates the following WP_Query argument:
Post
The PostQuery
class provides methods for filtering posts based on various post-related parameters. These methods allow you to specify the post type, post ID, post slug, post parent, and more.
postType($type)
The postType($type)
method allows you to specify the post type you want to query. You can provide the post type as a parameter. Here's an example:
This generates the following WP_Query argument:
postId($id)
The postId($id)
method allows you to query a specific post by its ID. You can provide the post ID as a parameter. For example:
This generates the following WP_Query argument:
postSlug($slug)
The postSlug($slug)
method allows you to query a specific post by its slug. You can provide the post slug as a parameter. For example:
This generates the following WP_Query argument:
postParent($parentID)
The postParent($parentID)
method allows you to query posts that have a specific parent post. You can provide the parent post ID as a parameter. For example:
This generates the following WP_Query argument:
whereParentIn($parentIDs)
The whereParentIn($parentIDs)
method allows you to query posts that have parent posts specified by their IDs. You can pass an array of parent post IDs to this method. For example:
This generates the following WP_Query argument:
whereParentNotIn($parentIDs)
The whereParentNotIn($parentIDs)
method allows you to exclude posts that have parent posts specified by their IDs. You can pass an array of parent post IDs to this method. For example:
This generates the following WP_Query argument:
whereIn($postIDs)
The whereIn($postIDs)
method allows you to query posts with specific IDs. You can pass an array of post IDs to this method. For example:
This generates the following WP_Query argument:
whereNotIn($postIDs)
The whereNotIn($postIDs)
method allows you to exclude posts with specific IDs. You can pass an array of post IDs to this method. For example:
This generates the following WP_Query argument:
slugIn($slugs)
The slugIn($slugs)
method allows you to query posts with specific slugs. You can pass an array of post slugs to this method. For example:
This generates the following WP_Query argument:
Note: 'pagename' and 'page_id'
Unlike WP_Query, the PostQuery
class does not provide separate methods for 'pagename' and 'page_id' parameters. Instead, you can use 'name' and 'p' parameters while specifying the 'post_type' as 'page' to achieve the equivalent results:
This generates the following WP_Query argument:
Password
The PostQuery
class provides methods to filter posts based on their password protection status and the specific post password.
withPassword()
The withPassword()
method allows you to query posts that have a password protection set. You can use this method to retrieve posts that require a password to access. For example:
This generates the following WP_Query argument:
withoutPassword()
The withoutPassword()
method allows you to query posts that do not have a password protection set. You can use this method to exclude posts that require a password to access. For example:
This generates the following WP_Query argument:
withPassword($password)
The withPassword($password)
method allows you to query posts that have a specific post password set. You can provide the desired post password as a parameter. For example:
This generates the following WP_Query argument:
Status
The PostQuery
class allows you to filter posts based on their status using the postStatus()
method. This method helps you query posts with a specific status.
postStatus($status)
The postStatus($status)
method allows you to specify the status of posts you want to retrieve. You can provide the desired status as a parameter. For example:
This generates the following WP_Query argument:
You can use this method to query posts with different statuses such as 'publish,' 'draft,' 'pending,' or custom statuses defined in your WordPress installation. It provides precise control over the status of the posts you retrieve in your queries.
Comment Parameter
The PostQuery
class provides a method to filter posts based on the number of comments they have using the commentCount()
method. This method allows you to retrieve posts with a specific number of comments.
commentCount($count)
The commentCount($count)
method allows you to specify the number of comments a post should have in order to be retrieved in the query. You can provide the desired comment count as a parameter. For example:
This generates the following WP_Query argument:
Pagination
The PostQuery
class provides methods to control the pagination of query results. These methods allow you to specify the number of posts to retrieve per page, skip a certain number of posts, and more.
take($count), limit($count) or postsPerPage($count)
The take($count)
, limit($count)
, and postsPerPage($count)
methods allow you to specify the number of posts to retrieve per page. You can provide the desired post count as a parameter. For example:
These methods generate the following WP_Query argument:
You can use these methods to control the number of posts displayed on each page of your query results.
skip($count) or offset($count)
The skip($count)
and offset($count)
methods allow you to skip a certain number of posts in the query results. You can provide the desired skip count as a parameter. For example:
These methods generate the following WP_Query argument:
You can use these methods to skip a specific number of posts, useful for creating paginated queries.
noPaging()
The noPaging()
method allows you to disable pagination entirely, retrieving all posts matching the query without any pagination. For example:
This generates the following WP_Query argument:
Use this method when you want to retrieve all matching posts in a single query, regardless of the number.
postsPerArchivePage($count)
The postsPerArchivePage($count)
method allows you to specify the number of posts to display per archive page. This is particularly useful for archive pages like category or tag archives. For example:
This generates the following WP_Query argument:
You can use this method to control the number of posts displayed on archive pages.
page($pageNumber)
The page($pageNumber)
method allows you to specify the page number when paginating query results. You can provide the desired page number as a parameter. For example:
This generates the following WP_Query argument:
Use this method when you want to retrieve a specific page of results in a paginated query.
ignoreStickyPosts()
The ignoreStickyPosts()
method allows you to exclude sticky posts from the query results. Sticky posts are posts that are pinned to the top of the list. For example:
This generates the following WP_Query argument:
Order
The PostQuery
class provides methods to control the order in which posts are retrieved. You can specify one or more orderby parameters to sort the query results based on various criteria.
orderBy($field, $order = 'DESC')
The orderBy($field, $order = 'DESC')
method allows you to specify the field by which the posts should be ordered and the order in which they should be sorted. You can provide the desired field and order as parameters. For example:
This method generates the following WP_Query argument:
Date
The PostQuery
class allows you to query posts based on date-related criteria using the DateQuery
class. This class provides methods to create complex date queries, allowing you to filter posts by their publication, modification, or custom dates.
dateQuery($callback)
The dateQuery($callback)
method allows you to define a complex date query using the DateQuery
class. You can pass a callback function to create the date query conditions. For example:
This method generates the following WP_Query argument:
You can use this method to create complex date queries that include conditions like before, after, and inclusive/exclusive settings.
date($column = 'post_date')
The date($column = 'post_date')
method within the DateQuery
class allows you to specify the column or type of date to query. You can choose from 'post_date,' 'post_modified,' or other custom date columns. For example:
before($date)
The before($date)
method within the DateQuery
class allows you to specify that the date should be before a certain point in time. You can provide the date in various formats, such as 'YYYY-MM-DD' or an array specifying 'year,' 'month,' 'day,' 'hour,' 'minute,' and 'second.'
after($date)
The after($date)
method within the DateQuery
class allows you to specify that the date should be after a certain point in time. Like the before()
method, you can provide the date in various formats.
between($start, $end)
The between($start, $end)
method within the DateQuery
class allows you to specify that the date should be between two points in time. You can provide the start and end dates in various formats.
created()
The modified()
method within the DateQuery
class allows you to specify that the date query should apply to the last modified date of the post, as opposed to the default 'post_date' column. This is useful for distinguishing between post creation and modification dates.
inclusive()
The inclusive()
method within the DateQuery
class allows you to specify that the date query should include posts that match the exact date and time specified. This is particularly useful when using the before()
and after()
methods.
Meta Query
The PostQuery
class allows you to perform custom queries based on post metadata using the MetaQuery
class. This class provides methods to create complex meta queries, allowing you to filter posts based on custom field values.
metaQuery($callback)
The metaQuery($callback)
method allows you to define a complex meta query using the MetaQuery
class. You can pass a callback function to create the meta query conditions. For example:
This method generates the following WP_Query argument:
meta($key)
The meta($key)
method within the MetaQuery
class allows you to specify the custom field key you want to query. For example:
Comparison Methods
The MetaQuery
class offers several methods to specify the comparison operations to perform on custom fields. You can chain these methods to build complex conditions.
ofType($type)
This method allows you to specify the type of comparison to use. Possible types are class constants such as MetaQueryBuilder::NUMERIC
, MetaQueryBuilder::CHAR
, MetaQueryBuilder::DATE
, etc. By default, the type is automatically determined based on the value provided during comparison.
Example of usage:
Note :
The detectValueType
method is used internally to automatically determine the data type of the value provided during comparison. It is called automatically when you use other comparison methods.
This method performs the following checks to determine the data type:
- If the value is an array, it takes the data type of the first element.
- If a data type is explicitly set using the
ofType
method, it uses that data type. - If the value is
null
, it defaults to theCHAR
data type. - If the value is
0
or1
, it uses theBINARY
data type. - If the value is a negative integer, it uses the
SIGNED
data type. - If the value is a non-negative integer, it uses the
UNSIGNED
data type. - If the value is a floating-point number, it uses the
DECIMAL
data type. - If the value is a string containing only a numeric date (e.g., '2022-01-01'), it uses the
DATE
data type. - If the value is a string containing only a numeric time (e.g., '12:00:00'), it uses the
TIME
data type. - If the value is a string containing both date and time (e.g., '2022-01-01 12:00:00'), it uses the
DATETIME
data type. - If none of the above conditions apply, it defaults to the
CHAR
data type.
equalTo($value)
This method specifies that the custom field must be equal to a certain value.
Example of usage:
notEqualTo(mixed $value)
This method specifies that the custom field must not be equal to a certain value.
Example of usage:
greaterThan($value)
This method specifies that the custom field must be greater than a certain value.
Example of usage:
greaterOrEqualTo($value)
This method specifies that the custom field must be greater than or equal to a certain value.
Example of usage:
lessThan($value)
This method specifies that the custom field must be less than a certain value.
Example of usage:
lessOrEqualTo($value)
This method specifies that the custom field must be less than or equal to a certain value.
Example of usage:
between(mixed $lowerBoundary, mixed $upperBoundary): self
This method specifies that the custom field must be between two given values.
Example of usage:
notBetween($lowerBoundary, $upperBoundary)
This method specifies that the custom field must not be between two given values.
Example of usage:
like(string $value): self
This method specifies a partial match of the custom field with a string.
Example of usage:
notLike($value)
This method specifies that the custom field must not partially match a string.
Example of usage:
in($values)
This method specifies that the custom field must match one of the values in a given array.
Example of usage:
notIn($values)
This method specifies that the custom field must not match any of the values in a given array.
Example of usage:
state($value)
The state($value)
method within the MetaQuery
class allows you to use the named meta queries and use this state for ordering. See this section of the documentation for more information.
Example of usage:
exists()
This method specifies that the custom field must exist (be defined).
Example of usage:
notExists()
This method specifies that the custom field must not exist (not be defined).
Example of usage:
metaQuery
Method Chaining
You can chain multiple meta()
methods to create complex meta queries. For example:
This generates a meta query with an 'OR' relation between the two conditions.
Nested Meta Queries
You can create nested meta queries by using the MetaQuery
class within the metaQuery()
callback. This allows you to create complex meta queries with multiple levels of conditions. For example:
Permission
The PostQuery
class allows you to query posts based on specific user permissions. You can use the following permission parameters to filter posts based on their accessibility to users.
userPermission(string $permission)
The userPermission
method is used to filter posts based on user permissions. It accepts one parameter:
-
$permission
(string): Specifies the type of permission to filter posts by. Valid values include:'readable'
: This permission filters posts that the user can read.'editable'
: This permission filters posts that the user can edit.
Filter posts that the user can read.
This method generates the following WP_Query argument:
Filter posts that the user can edit.
This method generates the following WP_Query argument:
Invalid permissions
When an invalid permission is provided, all posts are returned in the generated WP_Query:
Mimetype
The PostQuery
class allows you to filter posts based on their MIME types. You can use the postMimeType
method to specify the MIME type(s) you want to filter by.
postMimeType(string|array $mimeTypes)
The postMimeType
method filters posts based on MIME type(s). It accepts one parameter:
$mimeTypes
(string|array): Specifies the MIME type(s) to filter posts by. You can provide a single MIME type as a string or an array of multiple MIME types.
Filter posts by a single MIME type (e.g., 'image/gif').
This method generates the following WP_Query argument:
Filter posts by an array of MIME types.
This method generates the following WP_Query argument:
Cache
The PostQuery
class provides methods for controlling caching behavior when querying posts.
cacheResults()
The cacheResults
method enables caching of query results. When you use this method, the query results will be cached for faster retrieval. It doesn't accept any parameters.
This method generates the following WP_Query argument:
updateMetaCache($update)
The updateMetaCache
method allows you to control whether post meta data is cached. You can specify whether to update the post meta cache or not using this method.
$update
(bool): Passtrue
to update the post meta cache orfalse
to disable it.
This method generates the following WP_Query argument:
updateTermCache($update)
The updateTermCache
method allows you to control whether post term data is cached. You can specify whether to update the post term cache or not using this method.
$update
(bool): Passtrue
to update the post term cache orfalse
to disable it.
This method generates the following WP_Query argument: