Created
May 31, 2024 21:04
-
-
Save rohjay/7226f445e0bcafdaa0b577b02141850d to your computer and use it in GitHub Desktop.
Example code that fixes common misspellings of words in seaches. Parameterize to taste π
This file contains 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 | |
add_action( 'pre_get_posts', function( $query ) { | |
if ( !$query->is_main_query() || !$query->is_search() ) { | |
return $query; | |
} | |
$common_misspellings = [ | |
'lorem' => ['lorum', 'lorm', 'lormu', 'lormum', 'lormum'], | |
'ipsum' => ['ipusm', 'ipsums', 'ipsumz', 'ipsumz', 'ispum'], | |
'dolor' => ['dolr', 'dolro', 'dloro', 'doolr'], | |
]; | |
$search_synonyms = []; | |
foreach ( $common_misspellings as $intended => $typos ) { | |
foreach ( $typos as $typo ) { | |
$search_synonyms[ $typo ] = $intended; | |
} | |
} | |
$search = $query->get( 's' ); | |
$search_parts = explode(' ', $search); | |
$reworked_search = []; | |
foreach ( $search_parts as $search_part ) { | |
$search_part = trim( $search_part ); | |
if ( !empty( $search_part ) && isset( $search_synonyms[ $search_part ] ) ) { | |
$search_part = $search_synonyms[ $search_part ]; | |
} | |
$reworked_search[] = $search_part; | |
} | |
$query->set( 's', join(' ', $reworked_search) ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment