Replace search keywords (whole words)

In case you need to replace certain whole words that the user enters to others (like synonyms), then use this custom code.

What is this, and where do I put this custom code?

add_filter( 'asp_query_args', 'asp_replace_search_keywords', 10, 2 );
function asp_replace_search_keywords( $args, $id ) {
  /**
   * Add as many words as you want. On the left side place the
   * word or words separated by comma to replace.
   * To the right side, place the single word to replace it with.
   */
  $replace = array(
    'word1' => 'word2',       // Replace 'word1' with 'word2'
    'word3, word4' => 'word5' // Replace 'word3' and 'word4' with 'word5'
  );

  // ----------------------------------------
  // Do not change anything below this line
  // ----------------------------------------
  foreach ( $replace as $k => $w ) {
    $kr = explode(',', $k);
    foreach ($kr as $krk => &$krv) {
      $krv = trim($krv);
      if ( $krv == '' ) {
        unset($kr[$krk]);
      } else {
        $krv = '/\b' . $krv . '\b/u';
      }
    }
    if ( count($krv) > 0 ) {
      $args['s'] = preg_replace($kr, $w, $args['s']);
    }
  }
  return $args;
}

Follow the instructions within the code to add/remove lines to the $replace array variable. Each key is a keyword or keywords separated by comma, and each value is the substitue keyword.

Last updated

Copyright Ernest Marcinko