I recently needed to figure out a way to send custom notifications from WordPress to Slack.
I tested out the Slack WordPress plugin which works well although it wasn’t suitable for the custom notifications I needed to setup.
I decided to write a some code that uses Slack’s Incoming Webhooks integration. Incoming Webhooks allow us to post messages to Slack using a standard HTTP request and JSON payload.
I’ve shared some example code below for you to use and expand upon in your projects, you’ll need to copy this function in your functions.php file or in a functionality plugin.
You’ll then need to code up a function for each notification, this allows you to control exactly when the notifications are sent and customise all of the content of the message to suit your project!
A simple example: Track user logins
To demonstrate how you can use this in a WordPress project, see the example function below that will send a notification to Slack when a user log’s into a WordPress site. I doubt this would be needed for many projects but I just wanted to share a simple example for this article ; )
As you can see this is reasonably straight forward to code, plus you can send off a message or notification when any of the WordPress actions hooks run! The coolest part is you can completely customise the content of the message and wrap it in any kind conditional logic you need.
- Replace most of the email notifications sent form WordPress with Slack notifications (This could apply for WooCommerce emails or Comment Notification emails).
- Send a direct message to a site admin if a plugin or WordPress core needs to be updated.
- Send a notification to the #sales Slack channel when an Contact Form has been submitted.
- Send a notification to an editor (on a multi author blog) to let them know a page/post is now pending review.
- Send a notification to a #news slack channel when a new post / product / page etc has been published.
- Even build your own highly customised version of Stream.
I’m currently using this:
- On one of my client sites, the marketing team is notified in Slack when a unique WordPress URL has been viewed by a customer.
- On one of my client sites, the sales team is notified when a particular Gravity Form has been submitted (they get a customised summary of the message and a link to the full entry).
- On my blog, I’m notified when an Instagram image was successfully imported into WordPress form the Instagram API (takes the unknown out of cron jobs).
Hopefully this post has sparked some ideas for your own notifications! If you code up any of your own custom WordPress and Slack notifications let me know so I can update this article!
- Slack supports Attachments so you can display “richly-formatted messages that stand out from regular chat messages” (this would be useful to colour code error messages).
- Slack also supports custom icon emoji, so you could have a WordPress logo for the WordPress bot ; )