Table of Contents
Table of Content
Retrieving Posts with the QueryBuilder #
nnhelpers
ships with a QueryBuilder to retrieve Posts from WordPress in a object-oriented style. If a Model was defined for the Repository, it will also automatically convert the Post-Arrays to Models.
Basic example #
$queryBuilder = \nn\wp::injectClass( \Nng\Nnhelpers\Utilities\QueryBuilder::class );
$posts = $queryBuilder->setPostType( 'myext_posttype' )->execute();
Settings limit and offset #
$queryBuilder
->setLimit( 10 )
->setOffset( 1 )
->execute();
Retrieve hidden records (not only "published" records) #
$queryBuilder
->setIgnoreEnableFields( true )
->execute();
Sorting of the results #
$queryBuilder
->setOrderings( 'post_title', 'ASC' )
->execute();
$queryBuilder
->setOrderings([
'post_title' => 'ASC',
'post_author' => 'DESC'
])
->execute();
AND Constraint #
$queryBuilder
->logicalAnd(
$queryBuilder->equals( 'post_title', 'Test' ),
$queryBuilder->equals( 'post_author', 'John' )
)
->execute();
Contraint options: #
// post_title = 'Test'
$queryBuilder->equals( 'post_title', 'Test' )
// meta._mytitle LIKE '%Wiesbaden%'
$queryBuilder->like( 'meta._mytitle', 'Wiesbaden' )
// JOIN with postmeta _startdate > 61223234
$queryBuilder->greaterThan( 'meta._startdate', 61223234 )
// JOIN with postmeta _startdate >= 61223234
$queryBuilder->greaterThanOrEqual( 'meta._startdate', 61223234 )
// JOIN with postmeta _startdate < 61223234
$queryBuilder->lessThan( 'meta._startdate', 61223234 )
// JOIN with postmeta _startdate <= 61223234
$queryBuilder->lessThanOrEqual( 'meta._startdate', 61223234 )
// JOIN with post-category IN (1,2,3)
$queryBuilder->in( 'category', [1,2,3] ),
// JOIN with post-category NOT IN (1,2,3)
$queryBuilder->notIn( 'category', [1,2,3] ),
Example in the Repository: #
<?php
namespace My\Extension\Domain\Repository\CPT;
use Nng\Nnhelpers\Domain\Repository\CPT\AbstractRepository;
class EntryRepository extends AbstractRepository
{
/**
* @param array $categoryUids
* @return array
*/
public function findForCategory( $categoryUids = [] )
{
$query = $this->createQuery();
$results = $query->logicalAnd(
$queryBuilder->in( 'category', $categoryUids )
)->execute();
return $results;
}
}
Example in the Controller: #
<?php
namespace My\Extension\Controller\Elementor;
use Nng\Nnhelpers\Controller\AbstractElementorController;
class MyController extends AbstractElementorController
{
/**
* @return void
*/
public function initializeView( $view = null )
{
$entryRepository = \nn\wp::injectClass( \My\Extension\Domain\Repository\CPT\MyRepository::class );
$query = $entryRepository->createQuery();
$query->logicalAnd(
$query->like( 'meta._myext_www', 'test' ),
$query->equals( 'meta._myext_city', 'Wiesbaden' )
);
$posts = $query->execute();
$this->view->assignMultiple([
'posts' => $posts
]);
}
}