barnythorpe/wp-fluent-queries

A fluent interface for constructing Wordpress queries in a safe, readable and clean manner.

0.1.0 2025-05-11 12:10 UTC

This package is auto-updated.

Last update: 2025-05-11 12:32:08 UTC


README

Latest Version Passing Tests Packagist Licence Last Commit

This package aims to create a fluent interface for constructing Wordpress queries in a safe, readable and clean manner.

🔧 Installation

composer require barnythorpe/wp-fluent-queries

🛠 Usage

Main Query Builders

The package provides query builders for the following:

The queries are constructed like so:

$builder = new PostQueryBuilder();
$builder
    ->postType('custom_post_type')
    ->postsPerPage(12)
    ->fields('ids');

or to make life simpler using the factory class:

$query = Query::post()
    ->postType('custom_post_type')
    ->postsPerPage(12)
    ->fields('ids');

Nesting Conditions

The package also provides a solution for the complex nested queries within the main wordpress queries:

These can be constructed using the group and condition classes and added to the main query like so:

$wp_query = Query::post()
    ->postType('custom_post_type')
    ->taxQuery(QueryGroups::tax(
        QueryConditions::tax()->taxonomy('example_tax')->terms([1, 2, 3])->field('term_id'),
        QueryConditions::tax()->taxonomy('another_tax')->terms([4, 5, 6])->field('term_id'),
    ))
    ->metaQuery(QueryGroups::meta(
        QueryConditions::meta()->compare('=')->type('CHAR')->key('foo')->value('bar'),
        QueryConditions::meta()->compare('!=')->type('CHAR')->key('baz')->value('qux'),
    ));

Please go to the Groups and Conditions tests for more examples: