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');
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');
Share
Improve this question
asked Sep 19, 2019 at 12:28
XATAXATA
6712 bronze badges
1 Answer
Reset to default 0Your 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');
?>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745145315a4613620.html
评论列表(0条)