Skip to content

Instantly share code, notes, and snippets.

@rohjay
Created May 31, 2024 21:04
Show Gist options
  • Save rohjay/7226f445e0bcafdaa0b577b02141850d to your computer and use it in GitHub Desktop.
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 πŸ‘
<?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