Created
February 7, 2025 02:18
-
-
Save VictorPietro/2204964eb95956f41bf2cdb2eb15e39e to your computer and use it in GitHub Desktop.
Search by year Jet Smart Filters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Search by year Jet Smart Filters */ | |
/* I want to share this code that allows you to search by year on Jet Smart Filters. */ | |
// 1. Create a meta field named 'example-date', which is type date saved as timestamp. | |
// 2. Set a query on query builder that will fetch all the years of a meta field (in this case, meta field is named example-date, created on step 1). | |
/* Add a query with this SQL (Advanced) on Query builder | |
SELECT year, label | |
FROM ( | |
SELECT 'all' AS year, 'All' AS label | |
UNION ALL | |
SELECT DISTINCT YEAR(FROM_UNIXTIME(meta_value)) AS year, YEAR(FROM_UNIXTIME(meta_value)) AS label | |
FROM wp_postmeta | |
WHERE meta_key = 'example-date' | |
) AS combined_results | |
ORDER BY | |
CASE | |
WHEN year = 'all' THEN 0 | |
ELSE 1 | |
END, | |
year DESC; | |
*/ | |
// 3. Using a Code Snippets plugin (or in functions.php of your child theme), I add this code to process filtering by year. | |
/* JetSmartFilters Filter by year */ | |
add_filter( 'jet-smart-filters/query/meta-query-row', function( $row ) { | |
if ( false !== strpos( $row['key'], 'by_years__' ) ) { | |
$args = explode( '__', $row['key'] ); | |
if ( count( $args ) < 2 ) { | |
return $row; | |
} | |
$meta_key = $args[1]; | |
$year = $row['value']; // Selected year from filter | |
if ( $year === 'all' ) { | |
// If the value is 'all', return the row without modifying the date filter | |
return $row; | |
} | |
$row['key'] = $meta_key; | |
$row['compare'] = 'BETWEEN'; | |
$row['type'] = 'NUMERIC'; | |
$row['value'] = array( | |
strtotime("{$year}-01-01 00:00:00"), | |
strtotime("{$year}-12-31 23:59:59"), | |
); | |
} | |
return $row; | |
}, 10, 1); | |
/* END JetSmartFilters Filter by year */ | |
// 4. Then create a radio filter, put 'label' as label and 'year' as value. On Data Source put JetEngine Query Builder (with the query you've just created), on "Use default filter" put 'all', "Equals comparison" and, most importantly, Query Variable should be "by_years__example-date" (change example-date to the meta field date you created on step one). | |
// 5. At last, on your frontend, place a radio filter, configure it as you normally do and it should be working right away. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment