Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created June 22, 2015 14:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/53d98d2a21ffad14e440 to your computer and use it in GitHub Desktop.
Save jchristopher/53d98d2a21ffad14e440 to your computer and use it in GitHub Desktop.
Programmatically implement SearchWP synonyms (you do not need the Term Synonyms extension)
<?php
add_filter( 'searchwp_term_in', 'my_find_synonyms', 10, 2 );
add_filter( 'searchwp_and_logic', '__return_false' );
function my_find_synonyms( $term, $engine ) {
global $searchwp;
if( ! class_exists( 'SearchWP' ) || version_compare( $searchwp->version, '2.0.3', '<' ) ) {
return $term;
}
$synonyms = array(
array(
'term' => 'ny',
'synonyms' => 'new york',
),
array(
'term' => 'nj',
'synonyms' => 'new jersey',
)
);
// we expect $term to be an array
if( is_string( $term ) ) {
$term = array( $term );
}
if( is_array( $term ) && is_array( $synonyms ) && !empty( $synonyms ) ) {
foreach( $synonyms as $synonym ) {
if( in_array( $synonym['term'], $term ) ) {
// there is a match, handle it
// break out where applicable
if( is_array( $synonym['synonyms'] ) && ! empty( $synonym['synonyms'] ) ) {
foreach( $synonym['synonyms'] as $maybe_synonym ) {
if( false !== strpos( $maybe_synonym, ' ' ) ) {
$maybe_synonym = explode( ' ', $maybe_synonym );
$synonym['synonyms'] = array_merge( $synonym['synonyms'], $maybe_synonym );
}
}
}
// merge everything together
$term = array_merge( $term, $synonym['synonyms'] );
}
}
}
$term = array_values( array_unique( $term ) );
$term = array_map( 'sanitize_text_field', $term );
return $term;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment