0

I want to replace word/character in wordpress search using the below code, though it works but not well.

E.G: if i search for only var it replaces var to foo and its works properly fine.

but if i add more words to it, it won't work anymore. E.G: if i search for happy var or some var link it probably doesn't work anymore.

I dont know why, here is the code below:

$search_replacements = array(
    '-' => ' ',
    '&' => 'replace2',
    'var' => 'foo'
);
function modify_search_term($request_vars) {
    global $search_replacements;
    if (!empty($request_vars['s']) && !empty($search_replacements[$request_vars['s']])) {
        $request_vars['s'] = $search_replacements[$request_vars['s']];
    }
    return $request_vars;
}
add_filter('request', 'modify_search_term');
0

Your code says, "If the search term isn't empty, and that exact search term is in my search replacements array, then replace the term." So, instead of this:

!empty($search_replacements[$request_vars['s']]

(which means, if this exact search term [$request_vars['s'] is in my $search_replacements array)

you'll need to instead loop through your search replacements array every time someone searches, and in the loop check whether the current search term is a substring of the current key in the loop. If so, then do your replacement - but only replace the substring and not the full string.

So, you'll need something like this:

<?php
function modify_search_term($request_vars) {
    // Global is usually not ideal - include the terms inside your filter.
    $search_replacements = array(
        '-' => ' ',
        '&' => 'replace2',
        'var' => 'foo'
    );
    // Loop through all of the Search Replacements
    foreach($search_replacements as $key => $replacement) {
        // Check for current Key in the Search Term
        if(stripos($request_vars['s'], $key)) {
            // Replace the Key with the Replacement - but don't affect the rest of the Search Term
            $request_vars['s'] = str_replace($key, $replacement, $request_vars['s']);
        }
    }
    // Always return
    return $request_vars;
}
add_filter('request', 'modify_search_term');
?>
  • I appreciate your effort, BUT the code you posted did not replace anything at all, it just gives back what I inputed – XATA Sep 19 at 16:25
  • Oops, one of the variable names was wrong. It is updated above. – WebElaine Sep 19 at 19:20
  • thank you a lot, it doesn't work properly though, if I search only the word var it does not replace var with foo, but if i only search happy var it works fine, I also notice that once if the word var starts the term it still doesn't work, e.g var smile it will not replace var smile to foo smile – XATA Sep 20 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.