How to sequentially order posts from multiple Custom Post Types by date within a single Bricks Builder query loop

Back home

This is a useful method if you are publishing events.

order posts date

Suppose you have a ‘Child Events’ CPT with a custom date field named ‘event-date-c’…and you also have a related parent event CPT named ‘Parent Events’ that has a custom date field named ‘event-date-p’…using Bricks, you can display both in a single query loop that has a custom class of ‘your-class’ assigned to the loop element…

Bricks Builder has a PHP filter that targets the element that has ‘your-class’ and then orders these events by their respective custom date field values, and only shows future events in the query loop – before the query runs! (as it’s not possible to do both these things at the same time using existing controls of the builder query loop).

Code below is adapted from here: https://academy.bricksbuilder.io/…/filter-bricks-posts…/ and should be added to your functions.php file.

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
    // Check if the global CSS classes are defined
    $global_css_classes = isset( $settings['_cssGlobalClasses'] ) ? \Bricks\Element::get_element_global_classes( $settings['_cssGlobalClasses'] ) : [];

    // Check if the 'events-ql' class is not present in the global CSS classes - 'events-ql' must be replaced with your query loop element class.
    if( empty( $global_css_classes ) || ! in_array( 'events-ql', $global_css_classes ) ) {
        // Return the original query parameters without modifications
        return $query_vars;
    }

    // Get the current date in 'Y-m-d' format
    $current_date = date( 'Y-m-d' );

    // Set the meta_query for filtering events based on date
    $query_vars["meta_query"] = [
        "relation" => "OR", // Use 'OR' relation to query any of the three fields
        "event_date_c" => [
            "key" => "event-date-c",
            "compare" => ">=", // Greater than or equal to the current date
            "value" => $current_date,
            "type" => "DATE",
        ],
        "event_date_p" => [
            "key" => "event-date-p",
            "compare" => ">=", // Greater than or equal to the current date
            "value" => $current_date,
            "type" => "DATE",
        ],
    ];

    // Set the orderby parameter for ordering events by date in ascending order
    $query_vars["orderby"] = [
        "event_date_c" => "ASC",
        "event_date_p" => "ASC",
    ];

    // Return the modified query parameters
    return $query_vars;
}, 10, 3 );

Have a project you'd like to discuss?

Book a discovery zoom call with Gerson.

Book Zoom Call