PHPackages                             jjgrainger/query - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. jjgrainger/query

ActiveLibrary[Database &amp; ORM](/categories/database)

jjgrainger/query
================

WordPress Query Builder

v0.2.0(3y ago)191213[1 PRs](https://github.com/jjgrainger/Query/pulls)1MITPHPPHP &gt;=7.2CI failing

Since Feb 14Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/jjgrainger/Query)[ Packagist](https://packagist.org/packages/jjgrainger/query)[ RSS](/packages/jjgrainger-query/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (2)Dependencies (2)Versions (4)Used By (1)

WordPress Query Builder v0.2.0
==============================

[](#wordpress-query-builder-v020)

> A fluent interface for creating WordPress Queries

[![tests](https://github.com/jjgrainger/Query/actions/workflows/tests.yml/badge.svg)](https://github.com/jjgrainger/Query/actions/workflows/tests.yml) [![codecov](https://camo.githubusercontent.com/e126f80a68ffb3d39700725536772f322e3cf90696232da1d23d62008d398386/68747470733a2f2f636f6465636f762e696f2f67682f6a6a677261696e6765722f51756572792f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/jjgrainger/Query) [![Total Downloads](https://camo.githubusercontent.com/1d7909de32adfe78104b75e142c20c7f667823591b6f96deab3a39281fc288b9/68747470733a2f2f706f7365722e707567782e6f72672f6a6a677261696e6765722f71756572792f646f776e6c6f616473)](https://packagist.org/packages/jjgrainger/query) [![Latest Stable Version](https://camo.githubusercontent.com/0763983459f30cec81aef5dcfa42708f8d9a091f1aab00a05090932990846165/68747470733a2f2f706f7365722e707567782e6f72672f6a6a677261696e6765722f71756572792f762f737461626c65)](https://packagist.org/packages/jjgrainger/query) [![License](https://camo.githubusercontent.com/504c4c32f26ad84f83f72702725c078116c7144e0d5878166ccff43b7e2c0df8/68747470733a2f2f706f7365722e707567782e6f72672f6a6a677261696e6765722f71756572792f6c6963656e7365)](https://packagist.org/packages/jjgrainger/query)

Requirements
------------

[](#requirements)

- PHP &gt;= 7.2
- [Composer](https://getcomposer.org/)
- [WordPress](https://wordpress.org) 5.3.2

Installation
------------

[](#installation)

```
$ composer require jjgrainger/query

```

Usage
-----

[](#usage)

The `Query` class provides a fluent interface for create `WP_Query` in WordPress.

```
use Query\Query;

// Create a new WP_Query for the latest 3 products.
$results = Query::post_type( 'product' )->posts_per_page( 3 )->get();

// The above is the same as...
$args = [
    'post_type'      => 'product',
    'posts_per_page' => 3,
];

$results = new \WP_Query( $args );
```

### Creating Custom Query Classes

[](#creating-custom-query-classes)

Custom query classes can be created by extending the `Query` class. Custom query classes can encapsulate default parameters which can then be expanded upon with query methods.

For example, a `FeaturedPostsQuery` can be created to return posts with the 'featured' taxonomy term. The default query parameters are defined within the `setup()` method that receives a `Builder` instance.

```
use Query\Query;
use Query\Builder;

class FeaturedPostsQuery extends Query
{
    /**
     * Setup the initial query.
     *
     * @param  Builder $builder
     *
     * @return Builder
     */
    public function setup( Builder $builder ): Builder
    {
        // Setup a tax_query for posts with the 'featured' term.
        $tax_query = [
            [
                'taxonomy' => 'featured',
                'fields'   => 'slugs',
                'terms'    => [ 'featured' ],
            ],
        ];

        return $builder->where( 'tax_query', $tax_query );
    }
}
```

Once the query class is created it can be used through out the project in a vairety of ways.

```
use FeaturedPostsQuery as Featured;

// Returns a WP_Query object for posts with the featured term.
$results = Featured::get();

// Returns a WP_Query object for the latest 3 products with the featured term.
$results = Featured::type( 'products' )->limit( 3 )->get();

// Queries can be instantiated with an array of additional query arguments.
$args = [
    'post_type' => 'products',
];

// Create a query object.
$query = new Featured( $args );

// Modify the query and get the WP_Query object.
$results = $query->limit( 3 )->get();
```

### Custom Scopes

[](#custom-scopes)

Custom scopes can be added to the global `Query` using the static `addScope` method. One of the simplest ways to add a scope is with a closure.

```
// Create a new scope with a closure.
Query::addScope( 'events', function( Builder $builder ) {
    return $builder->where( 'post_type', 'event' );
} );

// Call the scope when needed.
$results = Query::events()->limit( 3 );
```

#### Custom Scope Classes

[](#custom-scope-classes)

Custom scope classes can be added to the global `Query`. The custom scope class will need to implement the `Scope` interface and contain the required `apply` method. The `apply` method should accept the query `Builder` as the first argument and any optional arguments passed via the scope. Once added to the `Query` class the scope will be available by the class name with the first letter lowecase.

```
// Create a custom scope class.
use Query\Scope;
use Query\Builder;

class PostID implements Scope {
    public function apply( Builder $builder, $id = null ) {
        return $builder->where( 'p', $id );
    }
}

// Add the scope to the Query.
Query::addScope( new PostID );

// Use the scope in the Query.
$results = Query::postID( 123 )->get();
```

Notes
-----

[](#notes)

- The library is still in active development and not intended for production use.
- Licensed under the [MIT License](https://github.com/jjgrainger/Query/blob/master/LICENSE)
- Maintained under the [Semantic Versioning Guide](https://semver.org)

Author
------

[](#author)

**Joe Grainger**

-
-

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance53

Moderate activity, may be stable

Popularity22

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~863 days

Total

2

Last Release

1421d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e75df324c03b826071d520965956f3bbb8353970080cdfb1c93a742ea0a4ee44?d=identicon)[jjgrainger](/maintainers/jjgrainger)

---

Top Contributors

[![jjgrainger](https://avatars.githubusercontent.com/u/904708?v=4)](https://github.com/jjgrainger "jjgrainger (51 commits)")

---

Tags

query-builderwordpresswordpress-php-librarywordpresswp\_query

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/jjgrainger-query/health.svg)

```
[![Health](https://phpackages.com/badges/jjgrainger-query/health.svg)](https://phpackages.com/packages/jjgrainger-query)
```

###  Alternatives

[dbout/wp-orm

WordPress ORM with Eloquent.

1279.6k1](/packages/dbout-wp-orm)[williarin/wordpress-interop

Interoperability library to work with WordPress database in third party apps

6610.9k2](/packages/williarin-wordpress-interop)[tiny-pixel/acorn-db

Eloquent database support for Acorn projects

388.7k](/packages/tiny-pixel-acorn-db)[devgeniem/better-wp-db-error

Better WordPress database error handling.

1161.3k](/packages/devgeniem-better-wp-db-error)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
