在robots.txt添加 Disallow: /?s=* 防止搜索引擎收录

禁止搜索大于10的字符串:

To return a 404 error when a user tries to search content length greater than 10 characters on your WordPress site, you can use a custom function in your theme’s functions.php file or create a custom plugin. Below is an example of how you can achieve this:

// Hook into the pre_get_posts action
add_action('pre_get_posts', 'custom_search_length');

function custom_search_length($query) {
    // Check if it's a search query
    if (is_search()) {
        // Get the search query
        $search_query = $query->query_vars['s'];

        // Check the length of the search query
        if (strlen($search_query) > 10) {
            // If the length is greater than 10, set the query to return no results
            $query->set('s', ''); // Setting the search query to empty to return no results
            $query->is_search = false; // Marking as not a search query
            $query->is_404 = true; // Marking as 404 error
            status_header(404); // Setting the HTTP status code to 404
        }
    }
}

With this code:

  • We hook into the pre_get_posts action, which allows us to modify the query before it’s executed.
  • We check if the current query is a search query using is_search().
  • If it’s a search query, we retrieve the search query and check its length.
  • If the length is greater than 100, we modify the query to return no results, mark it as not a search query, and mark it as a 404 error.

Make sure to place this code in your theme’s functions.php file or in a custom plugin. Once added, any search queries with a length greater than 10 characters will return a 404 error.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *