PHP code example of jjgrainger / query

1. Go to this page and download the library: Download jjgrainger/query library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jjgrainger / query example snippets


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

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

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

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

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