The best part of learning more about WordPress is understanding its almost limitless flexibility to cater for projects of all shapes and sizes. The most common method to expand the platform is through the use of the thousands of plugins readily available to install, but as you begin to get more confident, you may want to introduce some additional functionality yourself through code, and that is exactly what we will be doing in this article.
I was recently working for a client who required the ability to send an SMS to users when new deals were posted on their website. Putting aside the functionality which allowed users to update their privacy and acceptance settings, I ended up achieving the task by combining the SMS gateway service Twilio with a number of in-built WordPress functions.
You may have already read our article on How To Send SMS WooCommerce Order Notifications which also makes use of the same third-party service to send text messages, but in this article, we will be looking at how to send a text message of your choice, no plugin required.
Setting Up Your Twilio Account Keys
To begin with you will need to create a free Twilio account, this is the service that will handle the sending of the text message once triggered to do so by WordPress. If you use the link provided you will receive $10 free credit on your account to start with at no cost.
After your registration is complete you should be taken to your account dashboard as shown below.
You will then need to head to the dropdown menu located in the top left-hand corner and select the option ‘Create New Project‘.
Next comes a number of project setup steps asking for the following information:
- Project Name (I would recommend just using your website title)
- Email Verification (Either a personal or business email for verification and communication purposes only)
- Mobile Number Verification (Use a personal or business mobile number here, it will mainly be used for account verification and never anything public-facing, you can use the same number you provided when first creating your Twilio account)
Following these initial details you will start to be asked about your intended integration options, you can skip past these for now as we will be covering everything in this article. You can skip this stage by answering ‘No‘ to the questions regarding whether you are comfortable with coding, and then select ‘Skip To Dashboard‘.
All being well, you should now be taken back to your original dashboard with your newly created project now visible. Next up you should click ‘Get A Trial Number‘ and complete the short verification process, this should leave you with an account page which shows you a trial number, Account SID and Auth Key as shown below.
Now that we have the three keys required from Twilio, we can move onto the code in WordPress that will trigger the platform to send out the SMS messages.
Using wp_remote_post to trigger the Twilio API
The communication between WordPress and your Twilio account will exist by making use the Twilio REST API, if this is your first experience with an API then fear not as we will explain everything you need to know. We are not going to go into the depths as to what an API is here, but for now, all you really need to know is that is stands for an ‘Application Programming Interface’ and is basically a programmatic way for two different systems to communicate and pass information and functionality with ease.
In our example we need to use WordPress to send, or ‘post’, information over to Twilio such as the message and number we wish to send to, for Twilio to receive, understand, and process. Thankfully, WordPress has a function readily available to do just that in wp_remote_post(). Let’s get stuck into the code.
We can start with a very basic PHP function to add to our theme’s functions.php file. considering that the only things that might change as we reuse it are the SMS message and the number we wish to send to, we can set those as the two arguments.
We can also go ahead and add three variables for the values we kept aside from our Twilio set up, make sure to change the values to your own as labeled in the code!
function wpcodetips_send_sms( $smsMessage , $contactNumber ){ // Change to your account SID $accountSID = 'XXXXXXXXXXXXX'; // Change to your account Auth Key $authKey = 'XXXXXXXXXXXXX'; // Change to your account trial number $sendNumber = '+XXXXXXXXXXX'; }
Now that we have all the necessary values in place, we can introduce the function to post the data to the Twilio API, you might find the next block of code a little mind-blowing if this is fairly new to you. The principle of what is happening is that we will be sending information over to a URL which will be expecting to receive and process it, this information is also sent alongside an authorisation value to ensure you have the permission to do so.
I also fully recommend you read up the depths of the wp_remote_post() function as well here, unless you simply plan on copying the final code.
Before using this code there are two very important things to remember:
- Whilst your Twilio account is in trial mode you will only be able to send SMS messages to the number you verified within your account
- All mobile numbers handled by Twilio must be in the E.164 format to work
function wpcodetips_send_sms( $smsMessage , $contactNumber ){ // Change to your account SID $accountSID = 'XXXXXXXXXXXXX'; // Change to your account Auth Key $authKey = 'XXXXXXXXXXXXX'; // Change to your account trial number $sendNumber = '+XXXXXXXXXXX'; // The Twilio API Url $url = "https://api.twilio.com/2010-04-01/Accounts/".$accountSID."/Messages.json"; // The data being sent to the API $data = array( 'From' => $sendNumber, 'To' => $contactNumber, 'Body' => $smsMessage ); // Set the authorisation header $headers = array( 'Authorization' => 'Basic ' . base64_encode($accountSID . ':' . $authKey)); // Send the POST request and store the response in a variable $result = wp_remote_post($url, array( 'body' => $data, 'headers' => $headers)); // Return the response body to ensure it has worked return json_decode($result['body'], true); }
Quite a lot to take in there, but all being well you should be able to run the following code shortly followed by the SMS coming through on your phone! If you have any issues however then you can inspect the returned body message to help diagnose the problem.
$myMessage = "Hey this is my first SMS message sent through WordPress!"; $sendTo = '+012345678910'; wpcodetips_send_sms( $myMessage, $sendTo );
Moving On To External SMS Messages
Fingers crossed you tested the above code and everything is working as expected. Next, you will no doubt want to send a text message to someone other than yourself, and to do that you will need to both upgrade your Twilio account to paid, as well as purchase the monthly rental of a dedicated Twilio number.
Using the Twilio SMS service, you can expect to pay around $0.007 / £0.03p per message sent on average. You will also be required to rent a unique mobile number for use of the service at an additional cost of around $1 / 80p per month.
Conclusion
Congratulations, you have now have a very flexible function at hand to send SMS messages within your WordPress project. It goes without saying that if you plan to implement a feature such as this within your website then please always ask for permission before bombarding someone’s device.
We hope you have found this article useful. I would love to hear the way in which you are making use of it within your websites. On the other hand, if you are struggling to make it work then please let me know in the comments below and I will try my best to assist you!