Technology Sharing

[Wordpress tutorial] Add illegal keyword blocking to wordpress blog website

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Some websites are often searched maliciously, which annoys the webmasters. So how can we block malicious search keywords? Let's follow the editor to solve this problem.

Background settings preview:
image.png
Setup Tutorial:
1. Add the following code to the functions.php file of the current theme:

add_action('admin_init', 'ytkah_search_ban_key');
function ytkah_search_ban_key() {
    add_settings_field('ytkah_search_key', '搜索关键词屏蔽', 'ytkah_search_key_callback_function', 'reading');
    register_setting('reading','ytkah_search_key');
}
function ytkah_search_key_callback_function() {
    echo '<textarea name="ytkah_search_key" rows="10" cols="50" id="ytkah_search_key" class="large-text code">' . get_option('ytkah_search_key') . '</textarea>';
}
add_action('template_redirect', 'ytkah_search_ban');
function ytkah_search_ban(){
    if (is_search()) {
        global $wp_query;
        $ytkah_search_key = get_option('ytkah_search_key');
        if($ytkah_search_key){
            $ytkah_search_key = str_replace("rn", "|", $ytkah_search_key);
            $BanKey = explode('|', $ytkah_search_key);
            $S_Key = $wp_query->query_vars;
            foreach($BanKey as $Key){
                if( stristr($S_Key['s'],$Key) != false ){
                    wp_die('请不要搜索非法关键字');
                }
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2. Then, go to "Settings-Reading-Search keyword blocking-Add the search keywords you want to block" on the left sidebar of the backstage, such as the preview image setting, one keyword per line;
3. After setting up, we can try to search and see! The following picture is the result of my test:
image.png