Created
May 26, 2021 08:50
-
-
Save ahegyes/4ecfbc4275ffbf38543dd6d71015285e to your computer and use it in GitHub Desktop.
FacetWP fuzzy autocomplete
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
add_filter( 'query', function( $query ) { | |
if ( false !== strpos( $query, 'facet_display_value LIKE' ) ) { | |
preg_match( "/LIKE '%(.*?)%'/s", $query, $matches ); | |
$keywords = $matches[1]; | |
if ( ! empty( $keywords ) ) { | |
$old_where = "facet_display_value LIKE '%$keywords%'"; | |
$new_where = array(); | |
$keywords_boom = explode( ' ', $keywords ); | |
foreach ( dws_permutations( $keywords_boom ) as $permutation ) { | |
$permutation = implode( '%', $permutation ); | |
$new_where[] = "facet_display_value LIKE '%$permutation%'"; | |
} | |
$new_where = implode( ' OR ', $new_where ); | |
$query = str_replace( $old_where, "($new_where)", $query ); | |
} | |
} | |
return $query; | |
} ); | |
function dws_permutations( array $elements ) { | |
if ( count( $elements ) <= 1 ) { | |
yield $elements; | |
} else { | |
foreach ( dws_permutations( array_slice( $elements, 1 ) ) as $permutation ) { | |
foreach ( range( 0, count( $elements ) - 1 ) as $i ) { | |
yield array_merge( | |
array_slice( $permutation, 0, $i ), | |
array( $elements[0] ), | |
array_slice( $permutation, $i ) | |
); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment