Величавый users signup php. Отправляем письма активации

Much of the websites have a registration form for your users to sign up and thus may benefit from some kind of privilege within the site. In this article we will see how to create a registration form in PHP and MySQL.

We will use simple tags and also we will use table tag to design the Sign-Up.html webpage. Let’s start:

Listing 1 : sign-up.html

Sign-Up

Registration Form
Name
Email
UserName
Password
Confirm Password


Figure 1:

Description of sing-in.html webpage:

As you can see the Figure 1, there is a Registration form and it is asking few data about user. These are the common data which ask by any website from his users or visitors to create and ID and Password. We used table tag because to show the form fields on the webpage in a arrange form as you can see them on Figure 1. It’s looking so simple because we yet didn’t used CSS Style on it now let’s we use CSS styles and link the CSS style file with sing-up.html webpage.

Listing 2 : style.css

/*CSS File For Sign-Up webpage*/ #body-color{ background-color:#6699CC; } #Sign-Up{ background-image:url("sign-up.png"); background-size:500px 500px; background-repeat:no-repeat; background-attachment:fixed; background-position:center; margin-top:150px; margin-bottom:150px; margin-right:150px; margin-left:450px; padding:9px 35px; } #button{ border-radius:10px; width:100px; height:40px; background:#FF00FF; font-weight:bold; font-size:20px; }

Listing 3 : Link style.css with sign-up.html webpage



Figure 2:

Description of style.css file:

In the external CSS file we used some styles which could be look new for you. As we used an image in the background and set it in the center of the webpage. Which is become easy to use by the help of html div tag. As we used three div tag id’s. #button, #sing-up, and #body-color and we applied all CSS styles on them and now you can see the Figure 2, how much it’s looking beautiful and attractive. You can use many other CSS styles as like 2D and 3D CSS styles on it. It will look more beautiful than its looking now.

After these all simple works we are now going to create a database and a table to store all data in the database of new users. Before we go to create a table we should know that what we require from the user. As we designed the form we will create the table according to the registration form which you can see it on Figure 1 & 2.

Listing 3 : Query for table in MySQL

CREATE TABLE WebsiteUsers (userID int(9) NOT NULL auto_increment, fullname VARCHAR(50) NOT NULL, userName VARCHAR(40) NOT NULL, email VARCHAR(40) NOT NULL, pass VARCHAR(40) NOT NULL, PRIMARY KEY(userID));

Description of Listing 3:

One thing you should know that if you don’t have MySQL facility to use this query, so should follow my previous article about . from this link you will able to understand the installation and requirements. And how we can use it.

In the listing 3 query we used all those things which we need for the registration form. As there is Email, Full name, password, and user name variables. These variable will store data of the user, which he/she will input in the registration form in Figure 2 for the sing-up.

After these all works we are going to work with PHP programming which is a server side programming language. That’s why need to create a connection with the database.

Listing 4 : Database connection

Description of Listing 4:

We created a connection between the database and our webpages. But if you don’t know is it working or not so you use one thing more in the last check listing 5 for it.

Listing 5 : checking the connection of database connectivity

Description Listing 5:

In the Listing 5 I just tried to show you that you can check and confirm the connection between the database and PHP. And one thing more we will not use Listing 5 code in our sing-up webpage. Because it’s just to make you understand how you can check the MySQL connection.

Now we will write a PHP programming application to first check the availability of user and then store the user if he/she is a new user on the webpage.

Listing 6 : connectivity-sign-up.php

Description of connectivity-sign-up.php

In this PHP application I used simplest way to create a sign up application for the webpages. As you can see first we create a connection like listing 4. And then we used two functions the first function is SignUP() which is being called by the if statement from the last of the application, where its first confirming the pressing of sign up button. If it is pressed then it will call the SingUp function and this function will use a query of SELECT to fetch the data and compare them with userName and email which is currently entered from the user. If the userName and email is already present in the database so it will say sorry you are already registered

If the user is new as its currently userName and email ID is not present in the database so the If statement will call the NewUser() where it will store the all information of the new user. And the user will become a part of the webpage.



Figure 3

In the figure 3, user is entering data to sign up if the user is an old user of this webpage according to the database records. So the webpage will show a message the user is registered already if the user is new so the webpage will show a message the user’s registration is completed.



Figure 4:

As we entered data to the registration form (Figure 4), according to the database which userName and email we entered to the registration form for sing-up it’s already present in the database. So we should try a new userName and email address to sign-up with a new ID and Password.



Figure 5

In figure 5, it is confirming us that which userName and email id user has entered. Both are not present in the database records. So now a new ID and Password is created and the user is able to use his new ID and Password to get login next time.

Conclusion:

In this article we learnt the simplest way of creating a sign up webpage. We also learnt that how it deals with the database if we use PHP and MySQL. I tried to give you a basic knowledge about sign up webpage functionality. How it works at back end, and how we can change its look on front end. For any query don’t hesitate and comment.

Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it"s a dependency management tool for php similar to node"s npm.

To install Composer on your machine, check this post:

Installing Laravel on Windows:

Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".

STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".

STEP-2) Enter the following command.

Composer create-project laravel/laravel my_laravel_site --prefer-dist

Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.

STEP-3) Now it"s time to be patient as laravel installation is going to take some time.

STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.

Php artisan serve

STEP-5) This will show a message something like, "Laravel development server started:" along with an url.

STEP-6) Copy and paste the url on the browser. If things go right, you"d see the laravel welcome screen.

STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

Setting Application Key:

Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

Php artisan key:generate

Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.

Installing Specific Laravel Version:

The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:

Likewise you can easily install laravel using composer on windows . I hope you find this tutorial useful. Please share it on your social circle if you like it.

In this tutorial, we are going to be creating a user signup form that adds a user to a database, and then sends out a confirmation email that the user must click on before their account will be activated.

Need Some Help?

This tutorial will take you through the process from scratch, but if you prefer, you can use one of the many ready-made email signup forms on Envato Market. Here are a few of the most popular options.

1.

The Simple Signup Form jQuery Plugin will collect the visitor’s email address on your website in an effective, attention-grabbing way. It has a lot of optional customization options that you can set up in minutes.

2. Hype: SmartR Signup Form

Hype is a SmartR Sign Up form, preconfigured and added to any page in only one click. It harnesses the power of your users and their networks to actively increase sign-ups and exponentially grow your user base.

3. Beta Splash Page Email Signup Form

This is a very simple, yet stylish, form for your website where visitors can enter their email address (and name if desired) to be added to a contact list. It uses AJAX to submit and validate email and will also function if the user has JavaScript disabled.

Installation is quick and painless. This form does not require a database to function as it will create and store input into a CSV file.

So, we"ve cleaned up our variables, now let"s check to see if the user forgot any fields.

If(empty($username)){ //put code in me please } if(empty($password)){ //put code in me please } if(empty($email)){ //put code in me please }

Now we have three if statements that are checking if each field is empty. If the field is empty we are going to assign some variables.

To make things clean we are going to create an array that will hold the status of the signup process as well as any text we need to show the user.

Right above that piece of code, let"s create an array and a few variables.

$action = array(); $action["result"] = null; $text = array();

First we are creating a blank array called action and then setting an array value of result. Result is going to hold a value of either success or error. Next we create another blank array called text. This is going to hold any text we want to show the user during the signup.

Right now, our if statements that are checking our variables aren"t executing any code, so let"s go ahead and put some code inside the first if statement.

Put this code inside the username if statement.

$action["result"] = "error"; array_push($text,"You forgot your username");

Let"s say the user submits the form without a username. Our statement is going to run the code above. First it"s going to set the result field of our action array to error.

Then we are going to use array_push() to put some text into our text array. We are going to be using this same piece of code for the final two "if" statements so copy and paste that code into the last two if statements. You"ll probably want to change the text to match the current if statement.

Note: We are using array_push() in case we have multiple errors in the form submission. If all if statements are executed, the text array will looks like:

Array( => "You forgot your username", => "You forgot your password", => "You forgot your email")

We now need to check if we have any errors so we can continue on with the signup process.

Step 6: No Errors, Let"s Signup the User

We are going to check to see if our action array result value is set to error.

If($action["result"] != "error"){ //no errors, continue signup $password = md5($password); } $action["text"] = $text;

We are also running our password through the md5() function. This takes the password and returns a 32 character string that looks something like this: . It"s good practice to run the password through some sort of hashing function before putting it into the database. This prevents people from viewing the users passwords if your database is hacked.

A quick check of our action result value and we can continue on with the signup. If our result is error we will skip over all this code and output the errors to our user so they can make the necessary changes.

The last piece of this code we are putting the values of your text array into our action array.

Step 7: Adding the User to the Database

Place this code inside our last if statement.

If Statement checking for errors ... //add to the database $add = mysql_query("INSERT INTO `users` VALUES(NULL,"$username","$password","$email",0)"); if($add){ //the user was added to the database }else{ $action["result"] = "error"; array_push($text,"User could not be added to the database. Reason: " . mysql_error()); = }

We use mysql_query() and INSERT to insert the users information into the database. Next, we create another if statement checking to see if the user was added to the database. We do this by checking if the $add variable is true or false.

If the user is added we can continue on with the signup; if not we are going to assign some familiar variables and stop the signup.

When working with MySQL queries, we use the mysql_error() function if their are errors because it helps with debugging what is wrong with your queries. It will output text errors when something is wrong. This is good!

Step 8: Confirmation is Needed

The user has submitted the form, everything checks out and they"re now living in the database. We want the user to be able to use their account, so let"s setup the confirmation.

If added check ... //get the new user id $userid = mysql_insert_id(); //create a random key $key = $username . $email . date("mY"); $key = md5($key); //add confirm row $confirm = mysql_query("INSERT INTO `confirm` VALUES(NULL,"$userid","$key","$email")"); if($confirm){ //let"s send the email }else{ $action["result"] = "error"; array_push($text,"Confirm row was not added to the database. Reason: " . mysql_error()); }

To make things easy, let"s assign the new user id to a variable so we can use it later. We do this by using m ysql_insert_id() . This will set $userid to whatever the new user"s ID is.

Next we create the random key for that specific user. We create a variable named key and fill it with a value of the username, email and date. The string will look like [email protected]. After that we use the md5() function to convert it to a random string that is unique to that user.

Using mysql_query() and INSERT again, we put the new user ID, the key and the users email into the database.

Step 9: Setting up the Email Templates

We are going to take a break from the PHP coding and create two new files. For the sake of being quick and easy we are actually going to use two templates that I"ve included with this tutorial. The two files we"re going to be looking at are signup_template.html and signup_template.txt . Swift lets us assign an HTML as well as a TXT version of the email incase the users email client doesn"t support HTML emails.

Open up signup_template.html Note: You can read up on HTML in emails over at carsonified. We aren"t going to be editing this file, i"m just going to explain whats going on and then you can play around with it once the tutorial is complete. The most important part of this file is the tags that look like {USERNAME} and confirm.php?email={EMAIL}&key={KEY} . We are going to write a function that uses this template and replaces those tags with the variables from our form.

Step 10: The Template Function

Open up inc/php/functions.php and place this code inside.

Function format_email($info, $format){ //set the root $root = $_SERVER["DOCUMENT_ROOT"]."/dev/tutorials/email_signup"; //grab the template content $template = file_get_contents($root."/signup_template.".$format); //replace all the tags $template = ereg_replace("{USERNAME}", $info["username"], $template); $template = ereg_replace("{EMAIL}", $info["email"], $template); $template = ereg_replace("{KEY}", $info["key"], $template); $template = ereg_replace("{SITEPATH}","http://site-path.com", $template); //return the html of the template return $template; }

format_email() is taking two variables which will be used in index.php. The first is our form information array and the second is format. We have a format variable so we can re-use this array for both the HTML and TXT versions of the template.

First we set the root. This points to the folder that the templates are hosted.

Next we open up the contents of our template and assign it to a variable.

Now we are going to use ereg_replace() to replace our {USERNAME} tags in our template with the content from our form. It"s basically just a super simple template system.

Lastly we return the template variable which holds all the html.

Explanation: In a nutshell, format_email() opens up our template files, takes the HTML and assigns it to our variable. This is just a cleaner way then assigning all the HTML in the function itself.

Step 11: Sending the Email

We are going to write another function to deal with Swift and sending the emails.

Function send_email($info){ //format each email $body = format_email($info,"html"); $body_plain_txt = format_email($info,"txt"); //setup the mailer $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance(); $message ->setSubject("Welcome to Site Name"); $message ->setFrom(array("[email protected]" => "Site Name")); $message ->setTo(array($info["email"] => $info["username"])); $message ->setBody($body_plain_txt); $message ->addPart($body, "text/html"); $result = $mailer->send($message); return $result; }

Just like format_email() , send_email() takes our info array as a variable. The first part of the function we assign two variables, $body and $body_plain_text . We are using format_email() to assign the HTML values of our template to each variable. Now comes the good part. We have setup the swift instance using Swift_MailTransport:newInstance() and then setup the mailer using Swift_Mailer::newInstance($transport) ;

We create a new instance of the Swift message and start to assign some variables to this instance. We set the subject, from email and to email address and then use setBody() to assign out text version of the email to the mailer instance. To add the HTML version we use addPart() . The send() function takes care of the sending of the email and then we return the result. Alright, we have our email create and send functions written, let"s go back to index.php and start to wrap up the main signup.

Step 12: Did we Send? Shall we Confirm?

Our last bit should"ve been the if statement checking if the confirm row was created.

Let"s send the email and check if everything went though alright.

If confirm ... //include the swift class include_once "inc/php/swift/swift_required.php"; //put info into an array to send to the function $info = array("username" => $username, "email" => $email, "key" => $key); //send the email if(send_email($info)){ //email sent $action["result"] = "success"; array_push($text,"Thanks for signing up. Please check your email for confirmation!"); }else{ $action["result"] = "error"; array_push($text,"Could not send confirm email"); }

Without the Swift class we can"t send out any emails, so in our first line, we are including the swift class. We need to send our information to both of our new functions, so we create a new array and assign our variables to it. I know I know, more if statements, but we need to check for errors to make it easier for the users. You always have to assume that users will make every possible mistake imaginable.

We wrap our send_email() function in another if statement as well as passing the $info array. If the email is sent we assign a value of success and thank the user for signing up. If there are errors we use the familiar variables. So now, we are almost done with the signup, just one last function needs to be created. Even though we are assigning all these error/success variables and text we haven"t displayed this information to the user.

Move back to functions.php and paste this code.

//cleanup the errors function show_errors($action){ $error = false; if(!empty($action["result"])){ $error = "

    "."\n"; if(is_array($action["text"])){ //loop out each error foreach($action["text"] as $text){ $error .= ""."\n"; } }else{ //single error $error .= "

    $action

    "; } $error .= "
"."\n"; } return $error; }

This may seem confusing but it"s really just making our success/errors looks nice.

First it checks to see if the array is empty so we aren"t executing the code when it isn"t needed.

Next it creates a ul tag and applies the result as a class. This will either be success or error and is aesthetic only.

We then check to see if the text variable is an array or simply a string. If it"s a string, we wrap it in an li. If it"s an array we loop through each array item and wrap it in an li.

Lastly, we close the ul and return the entire string.

If we move back to index.php and place this code right after including header.php we can wrap up this section.

Header include ...

A quick little explanation. We are taking all the values of our action array and passing it to the show_errors() function. If there is any content it returns a nice unordered list.

Step 13: Confirming the User

We should have a good grip on how the script is functioning; so for this next script I"m going to give you the entire chunk of code and then go through it with you.

Open up confirm.php and paste this in-between the header include and your show_errors() function.

//setup some variables $action = array(); $action["result"] = null; //quick/simple validation if(empty($_GET["email"]) || empty($_GET["key"])){ $action["result"] = "error"; $action["text"] = "We are missing variables. Please double check your email."; } if($action["result"] != "error"){ //cleanup the variables $email = mysql_real_escape_string($_GET["email"]); $key = mysql_real_escape_string($_GET["key"]); //check if the key is in the database $check_key = mysql_query("SELECT * FROM `confirm` WHERE `email` = "$email" AND `key` = "$key" LIMIT 1") or die(mysql_error()); if(mysql_num_rows($check_key) != 0){ //get the confirm info $confirm_info = mysql_fetch_assoc($check_key); //confirm the email and update the users database $update_users = mysql_query("UPDATE `users` SET `active` = 1 WHERE `id` = "$confirm_info" LIMIT 1") or die(mysql_error()); //delete the confirm row $delete = mysql_query("DELETE FROM `confirm` WHERE `id` = "$confirm_info" LIMIT 1") or die(mysql_error()); if($update_users){ $action["result"] = "success"; $action["text"] = "User has been confirmed. Thank-You!"; }else{ $action["result"] = "error"; $action["text"] = "The user could not be updated Reason: ".mysql_error();; } }else{ $action["result"] = "error"; $action["text"] = "The key and email is not in our database."; } }

Most of this should look very familiar; so I"m going to skip ahead and check if the key is in the database section.

Again, we use mysql_query() to get any rows in the database where the email and key are equal to the keys provided by the users email.

We use mysql_num_rows() to check if the number of rows returned is greater than 0.

If the email and key are in the database we grab all the information from the database using mysql_fetch_assoc() .

Now that the user has confirmed his account, we need to update the database and set the active row to 1.

We use mysql_query() again, but instead of INSERT we use UPDATE to update the active row to 1 where the user ID is the same as our current users ID.

To clean everything up we use mysql_query() and DELETE to remove the confirmation row from the database. This makes sure that the user can"t come back to this page and reconfirm. It also keeps the database nice and clean.

Conclusion

We"ve covered many different areas in this tutorial. We downloaded and included a 3rd party script to deal with sending the emails, implemented simple form validation as well as created a super simple template system to style our emails. If you"re new to MySQL we"ve touched on the three most common functions in MySQL so you should have no problem completing some more advanced tutorials.

Final Notes

  • I"ve used Swift Mailer as our email deployment script which can be downloaded here: http://swiftmailer.org/
  • I"ve also used button styles provided by Zurb. Be sure to check them out and give them some love. http://www.zurb.com/blog_uploads/0000/0485/buttons-02.html

Thanks for reading and be sure to visit me on

Создаем собственную страницу регистрации для мультисайта взамен стандартной wp-signup.php .

В обычной установке WordPress страницу регистрации (авторизации, сброса пароля) выводит файл wp-login.php .

  • /wp-login.php - авторизация
  • /wp-login.php?action=register - регистрация
  • /wp-login.php?action=lostpassword - сброс пароля

Для мультисайта в wp-login.php есть отдельные условия. Так, при переходе по ссылке /wp-login.php?action=register на мультисайте, WordPress сделает редирект на страницу /wp-signup.php . Во многих темах страница выглядит не очень привлекательно, поэтому мы сделаем свою собственную.

Основной сайт сети

По умолчанию, WordPress открывает страницу регистрации (wp-signup.php) на основном домене (сайте) сети. Тем не менее, можно сделать отдельную страницу регистрации для каждого сайта сети, даже если у них разные темы. Мы будем рассматривать случай, когда на всех сайтах сети есть своя собственная страница регистрации, но используется одинаковая тема и сайты различаются лишь языком. Если используются разные темы, потребуется написать больше кода.

functions.php?

Нет. Имя этого файла, кажется, упоминается в любой статье про WordPress. В нашем случае, с учетом того, что функционал регистрации рассчитан на несколько сайтов, имеет смысл вынести его в MU-плагины, которые загружаются при открытии любого сайта.

Лирическое отступление

Стоит отметить, что MU-плагины загружаются раньше обычных плагинов и до полной загрузки ядра WordPress, поэтому вызов некоторых функций может привести к фатальным ошибкам в PHP. Подобная «ранняя» загрузка имеет и свои плюсы. Скажем внутри любой темы нельзя цепляться к некоторым экшенам, которые срабатывают еще до загрузки файла functions.php из темы. Примером этого могут служить экшены из плагина Jetpack вида jetpack_module_loaded_related-posts (related-posts - название модуля) с помощью которых возможно отслеживать активность модулей в Jetpack. К этому экшену невозможно «прицепиться» из файла темы, потому что экшен уже сработал до загрузки темы - плагины загружаются раньше тем. Взглянуть на общую картинку порядка загрузки WordPress можно на странице Action Reference в кодексе .

Порядок в файлах

MU-плагины могут содержать любое количество файлов и любую стуктуру, которая покажется вам логичной. Я придерживаюсь примерно такой иерархии:

|-mu-plugins |-|-load.php |-|-|-selena-network |-|-|-|-signup |-|-|-|-|-plugin.php |-|-|-|-|-... |-|-|-|-jetpack |-|-|-|-|-plugin.php

В файле load.php подключаются все необходимые «плагины» для нашей сети:

// Load Traslates for all addons load_muplugin_textdomain ("selena_network", "/selena-network/languages/"); // Network Signup require WPMU_PLUGIN_DIR . "/selena-network/signup/plugin.php"; // Another plugins // require WPMU_PLUGIN_DIR ...

Внутри папки selena-network хранятся папки плагинов, в каждой есть свой plugin.php , которые мы и подключаем в load.php . Это дает гибкость и возможность быстро отключать и включать некоторые вещи.

Адрес страницы регистрации

Чтобы указать адрес страницы регистрации, используется фильтр wp_signup_location . Его можно найти внутри файла wp-login.php и именно он отвечает за редирект на wp-signup.php .

Case "register" : if (is_multisite()) { wp_redirect(apply_filters("wp_signup_location", network_site_url("wp-signup.php"))); exit;

Добавим свою функцию в mu-plugins/selena-network/signup/plugin.php , которая будет отдавать адрес страницы регистрации на текущем сайте:

Function selena_network_signup_page ($url) { return home_url () . "/signup/"; } add_filter ("wp_signup_location", "selena_network_signup_page", 99);

selena_network - префикс, который я использую в именах всех функций внутри MU-плагинов на своем сайте для избежания коллизий, его следует заменить на свой собственный уникальный префикс. Приоритет добавления фильтра 99, потому что некоторые плагины, например bbPress и BuddyPress могут перезаписать этот адрес на свой собственный (MU-плагины загружаются раньше, чем обычные плагины, см. выше). Обратите внимание, что используется home_url() , вместо network_site_url() , чтобы оставить посетителя на том же домене. В качестве адреса можно использовать любой URL.

Создание страницы

Теперь создадим страницу с адресом site.com/signup/ через обычный интерфейс, а в папке дочерней темы шаблон для нашей новой страницы - page-signup.php . Вместо слова «signup» можно использовать уникальный ID.

Внутри нового шаблона необходимо выполнить вызов функции selena_network_signup_main() , которая будет выводить форму регистрации.

Стоит заметить, что весь процесс с шаблонами не обязателен и вместо этого можно создать свой шорткод, который будет также вызывать функцию selena_network_signup_main() .

wp-signup.php и wp-activate.php

Теперь займемся созданием функции, которая будет выводить форму регистрации. Для этого скопируем файлы wp-signup.php и wp-activate.php из корня WordPress в mu-plugings/selena-network/signup/ (и не забываем их подключить внутри mu-plugins/selena-network/signup/plugin.php). Дальнейшие манипуляции с файлами крайне сложно и долго описывать, поэтому прийдется сделать их самостоятельно. Я лишь опишу что именно надо сделать и опубликую исходные файлы своего проекта:

  1. В начале файла удалить все require , вызов функций и прочий код вне функций.
  2. Переименовать все функции, добавив к именам уникальные префиксы.
  3. Нижнюю часть кода wp-signup.php обернуть в функцию selena_network_signup_main и в ее самом начале написать global $active_signup; .
  4. Заменить верстку на свою собственную в нужных местах.

Внутри wp-activate.php необходимо сделать примерно тоже самое:

  1. Удалить весь код вне функций, обернуть верстку в отдельную функцию.
  2. Изменить верстку в местах, где это необходимо.

Файл wp-activate.php отвечает за страницу активации аккаунта. Как и со страницей регистрации для нее необходимо создать отдельный шаблон, внутри которого вызывать функцию из файла wp-activate.php .

Отправляем письма активации

Страница регистрации отправляет посетителю письмо со ссылкой на активацию аккаунта. По умолчанию этим занимается функция wpmu_signup_user_notification() из файла ms-functions.php . Ее функционал можно заимствовать для своей функции. Причина, по которой необходимо отказаться от использования этой функции - она отправляет ссылку активации аккаунта с wp-activate.php . «Выключить» же эту функцию можно с помощью фильтра wpmu_signup_user_notification отдавая по нему false (если этого не cделать, письмо активации будет отправляться дважды, окей, на самом деле два разных письма).

Function armyofselenagomez_wpmu_signup_user_notification($user, $user_email, $key, $meta = array()) { // ... // Код из функции wpmu_signup_user_notification() wp_mail($user_email, wp_specialchars_decode($subject), $message, $message_headers); return false; } add_filter("wpmu_signup_user_notification", "armyofselenagomez_wpmu_signup_user_notification", 10, 4);

В результате страница регистрации в теме Селена стала выглядеть намного чище и аккуратней.

Заключение

В интернете множество других не очень правильных способов того, как сделать тоже самое - редиректы Apache, AJAX-формы, которые не будут работать без Java Script и т. п. Все это мне не очень понравилось, поэтому я постарался сделать это максимально правильно на своем собственном сайте.

Замечу, что править файлы следует осторожно и стараться не сильно отходить от исходных, чтобы в дальнешйем, в случае если WordPress изменит файлы wp-signup.php и wp-activate.php , их проще было сравнивать между собой для поиска изменений.

Не забывайте смотреть в исходный код всех описанных выше функций, чтобы полностью разобраться с тем, что и как происходит внутри кода.

Бонус. Защита от спамеров

Даже самые маленькие сайты на WordPress часто подвергаются налету спам-регистраций. Можно писать бесконечные условия для фильтрации ботов, зачастую больше похожие на попытку создать искусственный интеллект 🙂 В случае мультисайта мне очень помог обычный редирект в Apache, с помощью которого при открытии /wp-signup.php и /wp-acitvate.php я попросил выдавать 404 (я не эксперт по настройке Apache, поэтому мои правила могут быть не очень правильными).

RewriteEngine On RewriteBase / RewriteRule ^wp-signup\.php - RewriteRule ^wp-activate\.php - # BEGIN WordPress # Правила от WordPress по умолчанию не трогаем:) # ... # END WordPress

P. S. Я стараюсь максимально детально описывать некоторые сторонние вещи, потому что когда начинал я, порой некому было подсказать и объяснить многие вещи. Также я считаю, что подобные небольшие наводки на другие материалы кого-нибудь подтолкнут к изучению чего-то нового и расширению своей области знаний. В записях RewriteRule используются регулярные выражения, они совсем не сложные, например, символ ^ означает начало строки.

Advertisements