BLOGRON BLOGRON COMMUNITY

Author Topic: How to Restrict Usernames in WordPress Without a Plugin?  (Read 483 times)

delwar

  • Delwar Jahan
  • Administrator
  • Full Member
  • *****
  • Posts: 115
  • Popularity: +20/-5
  • I am the Moderator Bitch!
    • View Profile
    • BLOGRON
How to Restrict Usernames in WordPress Without a Plugin?
« on: October 28, 2022, 12:13:28 pm »
Add this code your theme's functions.php file.

*Remember to replace content of the “restricted array” with the usernames you want to restrict.

Code: [Select]
<?php
   
function wpsnippet_validate_username($valid$username) {
   
$restricted = array(&#39;profile&#39;, &#39;directory&#39;, &#39;domain&#39;, &#39;download&#39;, &#39;downloads&#39;, &#39;edit&#39;, &#39;editor&#39;, &#39;email&#39;, &#39;ecommerce&#39;, &#39;forum&#39;, &#39;forums&#39;, &#39;favorite&#39;, &#39;feedback&#39;, &#39;follow&#39;, &#39;files&#39;, &#39;gadget&#39;, &#39;gadgets&#39;, &#39;games&#39;, &#39;guest&#39;, &#39;group&#39;, &#39;groups&#39;, &#39;homepage&#39;, &#39;hosting&#39;, &#39;hostname&#39;, &#39;httpd&#39;, &#39;https&#39;, &#39;information&#39;, &#39;image&#39;, &#39;images&#39;, &#39;index&#39;, &#39;invite&#39;, &#39;intranet&#39;, &#39;indice&#39;, &#39;iphone&#39;, &#39;javascript&#39;, &#39;knowledgebase&#39;, &#39;lists&#39;,&#39;websites&#39;, &#39;webmaster&#39;, &#39;workshop&#39;, &#39;yourname&#39;, &#39;yourusername&#39;, &#39;yoursite&#39;, &#39;yourdomain&#39;);
   
$pages get_pages();
   foreach (
$pages as $page) {
      
$restricted[] = $page->post_name;
   }
   if(!
$valid || is_user_logged_in() && current_user_can(&#39;create_users&#39;) ) return $valid;
   
$username strtolower($username);
   if (
$valid && strpos$username, &#39; &#39; ) !== false) $valid=false;
   
if ($valid && in_array$username$restricted )) $valid=false;
   if (
$valid && strlen($username) < 5$valid=false;
   return 
$valid;
   }
   
add_filter(&#39;validate_username&#39;, &#39;wpsnippet_validate_username&#39;, 10, 2);

   
function wpsnippet_registration_errors($errors) {
      if ( isset( 
$errors->errors[&#39;invalid_username&#39;] ) )
         
$errors->errors[&#39;invalid_username&#39;][0] = __( &#39;ERROR: Invalid username.&#39;, &#39;wpsnippet&#39; );
      
return $errors;
   }
   
add_filter(&#39;registration_errors&#39;, &#39;wpsnippet_registration_errors&#39;);
?>
I do what I love, Money Comes on the Way.

BLOGRON COMMUNITY

How to Restrict Usernames in WordPress Without a Plugin?
« on: October 28, 2022, 12:13:28 pm »