10th Sep '24
/
0 comments

Custom SQL Ordering for Sorting Events in Bricks

Custom SQL Ordering for Sorting Events in Bricks

Consider the following scenario.

CPT: eventCustom field: event_date (of type Date)

Sample posts with post titles matching the meta value for convenience:

Requirement:

Show the events ordered by the event date with all current/upcoming events in ascending order and then all past events in descending order.

After implementing the tutorial:

This Pro tutorial provides the steps to create a custom sorting system that orders events by displaying future events first in ascending order, followed by past events in descending order, all within a single database query in Bricks.

Split (multiple) queries and post-query PHP sorting using a Bricks filter are two other ways of getting the same result. But a custom SQL ORDER BY clause has several advantages like performance, scalability for large datasets and pagination support.

Single Tutorial Purchase Option

Lifetime access to this single tutorial can be purchased for $39 here.

Step 1

Create event CPT and a corresponding field group having event_date field.

Add event posts and populate the field for each. We shall only pull the events for which the event date has been set.

Step 2

Define a custom function to modify the ORDER BY clause for event queries.

Add the following in child theme's functions.php (w/o the opening PHP tag) or a code snippets plugin:

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Get access to all 626 Bricks code tutorials with BricksLabs Pro

Related Tutorials..

Pro
Term Parent Slug Data Attribute in Bricks

Term Parent Slug Data Attribute in Bricks

How we can set a data attributes on a child taxonomy dynamically based on the parent taxonomy.
Categories:
Pro
Excluding Duplicate Posts from Query Loops in Bricks

Excluding Duplicate Posts from Query Loops in Bricks

How to ensure that posts are not duplicated when two query loops are used on the same page.
Categories:
Pro
ACPT Gallery Field Query Loop in Bricks

ACPT Gallery Field Query Loop in Bricks

How we can output images from ACPT‘s Gallery field for posts as a grid using a query loop.
Categories:
Pro
Posts older than today in Bricks

Posts older than today in Bricks

How to display only posts that were published before today in a query loop.
Categories: