jjgrainger/query

This package is not installable via Composer 1.x, please make sure you upgrade to Composer 2+. Read more about our Composer 1.x deprecation policy.

WordPress Query Builder

0.1.0 2020-02-14 13:42 UTC

This package is auto-updated.

Last update: 2021-05-29 01:31:21 UTC


README

A fluent interface for creating WordPress Queries

Build Status codecov Total Downloads Latest Stable Version License

Requirements

Installation

$ composer require jjgrainger/query

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

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.
        $featured = [
            'taxonomy' => 'featured',
            'fields'   => 'slugs',
            'terms'    => [ 'featured' ],
        ];

        return $builder->taxonomy( $featured );
    }
}

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();

Notes

Author

Joe Grainger