xarxaprod-wp-plugin/includes/custom-field-ajuts-filter.php

83 lines
2.6 KiB
PHP
Raw Normal View History

2024-01-09 16:22:35 +01:00
<?php
/**
* Makes a filter for the custom post type ajut and its custom fields
*
* references:
* basic start
* https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/
*
* checkbox adaptation query filter
* https://barn2.com/blog/querying-posts-by-custom-field-acf/#array-based-fields
*
* @package Xarxaprod_wp_plugin
*/
// define the filter fields
// array of filters (field key => field name)
2024-01-27 18:31:59 +01:00
$GLOBALS['my_query_filters_ajut'] = array(
2024-02-22 23:46:36 +01:00
'fundtarget' => 'xxp_fund_target',
'fundsource' => 'xxp_fund_source',
'fundfield' => 'xxp_fund_field'
2024-01-09 16:22:35 +01:00
);
2024-01-27 18:31:59 +01:00
$GLOBALS['my_query_filters_ajut_dates'] = array(
2024-02-22 23:46:36 +01:00
'fundapplybegin' => 'xxp_fund_apply_begin',
'fundapplyend' => 'xxp_fund_apply_end'
//'fundcall' => 'xxp_fund_call',
2024-01-09 16:22:35 +01:00
);
// action
2024-01-27 18:31:59 +01:00
add_action('pre_get_posts', 'my_pre_get_posts_ajuts',10,1);
if ( ! function_exists('my_pre_get_posts_ajuts') ){
function my_pre_get_posts_ajuts( $query ) {
2024-01-09 16:22:35 +01:00
// bail early if is in admin
if( is_admin() ) { return; }
// bail early if not main query or plugin $the_query_ajut
// - allows custom code / plugins to continue working
if( !$query->is_main_query() ) return;
// loop over filters
2024-01-27 18:31:59 +01:00
foreach( $GLOBALS['my_query_filters_ajut'] as $key => $fieldname)
2024-01-09 16:22:35 +01:00
{
// continue if not found in url
if( empty($_GET[ $fieldname ]) ) { continue; }
// get original meta query
$meta_query = [];
$meta_query[] = $query->get('meta_query');
$meta_query[] = array('relation' => 'OR');
// get the values for this filter
2024-02-22 23:46:36 +01:00
// eg: http://domain.tdl/ajut/?xxp_fund_target=autonoma,entitat-publica
2024-01-09 16:22:35 +01:00
$filtervalues= explode(',', $_GET[ $fieldname ]);
// loop retreived values from checkboxes and filter them with REGEXP
2024-02-22 23:46:36 +01:00
// http://domain.tdl/ajut/?xxp_fund_target=autonoma&xxp_fund_field=circi
// http://domain.tdl/ajut/?xxp_fund_target=autonoma,entitat-publica&xxp_fund_field=dansa
2024-01-09 16:22:35 +01:00
foreach( $filtervalues as $filteredvalue )
{
// they are array based fields
// https://barn2.com/blog/querying-posts-by-custom-field-acf/#array-based-fields
$strippedvalue = sprintf( '^%1$s$|s:%2$u:"%1$s";', $filteredvalue, strlen( $filteredvalue ) );
// add our meta query to the original meta queries
$meta_query[] = array(
array(
'key' => $fieldname,
'value' => $strippedvalue,
'compare' => 'REGEXP',
),
);
}
// update the meta query arguments
$query->set('meta_query', $meta_query);
}
//always return
return;
2024-01-27 18:31:59 +01:00
}
2024-01-09 16:22:35 +01:00
}