changed associat search to OR instead of AND

This commit is contained in:
jorge 2024-05-15 09:13:16 +02:00
parent 76dc12f2ac
commit c95490660f
1 changed files with 15 additions and 20 deletions

View File

@ -38,8 +38,8 @@ if ( ! function_exists( 'my_pre_get_posts_associats' ) ){
// bail early if not main query or plugin $the_query_associat // bail early if not main query or plugin $the_query_associat
// - allows custom code / plugins to continue working // - allows custom code / plugins to continue working
if( !$query->is_main_query() ) return; if( !$query->is_main_query() ) return;
$query->set( 'posts_per_page', -1);
//$query->set( 'relation', 'AND');
// loop over filters // loop over filters
foreach( $GLOBALS['my_query_filters_associat'] as $key => $fieldname) foreach( $GLOBALS['my_query_filters_associat'] as $key => $fieldname)
@ -48,36 +48,31 @@ if ( ! function_exists( 'my_pre_get_posts_associats' ) ){
if( empty($_GET[ $fieldname ]) ) { continue; } if( empty($_GET[ $fieldname ]) ) { continue; }
// get original meta query // get original meta query
$meta_query = []; $meta_query = []; //avoids infinite nesting
$meta_query[] = $query->get('meta_query'); $meta_query[] = $query->get('meta_query');
$meta_query[] = array('relation' => 'OR');
// get the values for this filter // get the values for this filter
// eg: http://domain.tdl/associat/?xxp_associat_target=autonoma,entitat-publica // eg: http://domain.tdl/associat/?xxp_associat_target=autonoma,entitat-publica
$filtervalues= explode(',', $_GET[ $fieldname ]); $filtervalues= explode(',', $_GET[ $fieldname ]);
// loop retreived values from checkboxes and filter them with REGEXP // loop retreived values from checkboxes and filter them
// http://domain.tdl/associat/?xxp_associat_target=autonoma&xxp_associat_field=circi
// http://domain.tdl/associat/?xxp_associat_target=autonoma,entitat-publica&xxp_associat_field=dansa
foreach( $filtervalues as $filteredvalue ) foreach( $filtervalues as $filteredvalue )
{ {
// they are array based fields
// https://barn2.com/blog/querying-posts-by-custom-field-acf/#array-based-fields // add our meta query to the original meta queries
$strippedvalue = sprintf( '^%1$s$|s:%2$u:"%1$s";', $filteredvalue, strlen( $filteredvalue ) ); $meta_query['relation'] = 'OR';
// add our meta query to the original meta queries
$meta_query[] = array( $meta_query[] = array(
array( 'key' => $fieldname,
'key' => $fieldname, 'value' => $filteredvalue,
'value' => $strippedvalue, 'compare' => 'LIKE'
'compare' => 'REGEXP',
),
); );
} }
// update the meta query arguments // update the meta query arguments
$query->set('meta_query', $meta_query); $query->set('meta_query', $meta_query);
//$query->set('relation', 'AND');
} }
//echo '<pre>' . var_export($query, true) . '</pre>';
//echo '<pre>' . print_r($query,true) . '</pre>';
//always return //always return
return; return;
} }