Prefiltering Bricks Terms Query Loop

Let’s say there’s a Events CPT with a ‘Event Year’ custom taxonomy.

Sample event year names could be: 2021, 2022, 2024, 2025, 2028 etc.

We can set up a Terms query in Bricks to output these terms.

Result:

The reason 2021 is not present is because there are no posts that have been categorized with 2021.

Now the requirement is to output only the (non-empty) years that are in the future.

Like this:

This Pro tutorial shows how terms can be filtered based on their value using the bricks/terms/query_vars filter.

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

<?php

// Filter the terms query vars for the 'event-year' taxonomy to include only future years.
add_filter( 'bricks/terms/query_vars', function( $query_vars, $settings, $element_id ) {
    // If the element ID is not the one we want to target, return the query vars as is
    if ( $element_id !== 'uxlyeg' ) return $query_vars;
    
    // Get all the non-empty terms
    $terms = get_terms( ['taxonomy' => 'event-year'] );

    // Get the current year
    $current_year = date( 'Y' );

    // Pre-filter terms to include only future years using array_filter for dynamic comparison
    $future_terms = array_filter( $terms, function( $term ) use ( $current_year ) {
        return intval( $term->name ) > intval( $current_year );
    });

    // Extract term IDs from the filtered terms
    $term_ids = wp_list_pluck( $future_terms, 'term_id' );

    // Set the include query var to the filtered term IDs
    $query_vars['include'] = $term_ids;

    return $query_vars;
}, 10, 3 );

Replace uxlyeg with the Bricks ID of the element on which query loop is enabled.

Replace event-year with the taxonomy name/ID.