menu

Questions & Answers

Blocking Words From Input Box On Wordpress

We are able to block certain words from being inputted by the user, but they only get blocked if the exact blocked word is inputted.

For example the filter below will block if someone types in "word1" but will not block "word11".

How can the filter below be adapted, so that, as long as word1 is in any of the characters, this gets blocked, and "word11" or "word11133" etc gets blocked, as it contains the banned "word1"?

Trying to figure out a simple solution to the above?

The code that we are working with so far is:

add_action( 'pre_get_posts', 'wpse338558_intercept_banned_keywords' );
function wpse338558_intercept_banned_keywords ($query) {
  $banned = array ('word1','word2','word3');
  if (in_array ($query->query_vars['s'], $banned)) $query->s = '';
  }

Can add more things to the $banned array, but this requires thinking of every possible scenario, which isn't realistic.

Answers(1) :

you could try this :

add_action( 'pre_get_posts', 'wpse338558_intercept_banned_keywords' );
function wpse338558_intercept_banned_keywords ($query) {
  $banned = array ('word1','word2','word3');
  $search_string = $query->query_vars['s'];
  foreach($banned as $word){
    if (preg_match("/\b$word\b/i", $search_string)) {
      $query->s = '';
      break;
    }
  }
}
Comments:
2023-01-20 00:15:07
Thanks for that. Can't seem to get your snippet to work. Have tried adding if ( is_search() ) { as it's for the search input box on a wordpress site. Just need the box to empty and redirect to home page if one of the banned words is entered. Have also added wp_redirect( home_url() ); exit(); to the bottom as well.
2023-01-20 00:15:07
can u share the updated code u r using ?