82 lines
2.5 KiB
PHP
82 lines
2.5 KiB
PHP
|
<?php
|
||
|
/**
|
||
|
* Makes a filter for the custom post type convo 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)
|
||
|
$GLOBALS['my_query_filters'] = array(
|
||
|
'calltarget' => 'os_call_target',
|
||
|
'callsource' => 'os_call_source',
|
||
|
'callfield' => 'os_call_field'
|
||
|
);
|
||
|
$GLOBALS['my_query_filters_dates'] = array(
|
||
|
'callapplybegin' => 'os_call_apply_begin',
|
||
|
'callapplyend' => 'os_call_apply_end'
|
||
|
//'callcall' => 'os_call_call',
|
||
|
);
|
||
|
|
||
|
// action
|
||
|
add_action('pre_get_posts', 'my_pre_get_posts',10,1);
|
||
|
|
||
|
function my_pre_get_posts( $query ) {
|
||
|
|
||
|
// bail early if is in admin
|
||
|
if( is_admin() ) { return; }
|
||
|
|
||
|
// bail early if not main query or plugin $the_query_convo
|
||
|
// - allows custom code / plugins to continue working
|
||
|
if( !$query->is_main_query() ) return;
|
||
|
|
||
|
|
||
|
|
||
|
// loop over filters
|
||
|
foreach( $GLOBALS['my_query_filters'] as $key => $fieldname)
|
||
|
{
|
||
|
// 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
|
||
|
// eg: http://domain.tdl/convo/?os_call_target=autonoma,entitat-publica
|
||
|
$filtervalues= explode(',', $_GET[ $fieldname ]);
|
||
|
|
||
|
// loop retreived values from checkboxes and filter them with REGEXP
|
||
|
// http://domain.tdl/convo/?os_call_target=autonoma&os_call_field=circi
|
||
|
// http://domain.tdl/convo/?os_call_target=autonoma,entitat-publica&os_call_field=dansa
|
||
|
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;
|
||
|
}
|