Something I get asked a fair bit with regards to my plugins is how to send an alert during an event, for example, “when a job expires in WP Job Manager, how can I notify the user?”

Plugins which use custom post types, like WP Job Manager, are likely to use custom/standard post statuses too – it’s pretty common. Using these statuses you can easily hook-in a custom function and trigger and email.

This is a quick tutorial for hooking into a status change and sending an email for WP Job Manager.

Create a custom plugin, open up functions.php, or create a drop in

You need to place your code somewhere. I’d recommend a plugin or drop in to keep your code upgrade-safe, but you can also use the theme functions.php file. You can read about making plugins in the codex – I’ll focus on the code itself rather than this aspect.

Let’s create a class to house our functionality:

Find out the status you wish to act upon and hook into it

Job Manager uses WP core statuses plus 1 custom one called ‘expired’ (which is registered using the register_post_status function).

Generally, the flow goes something like:

  1. Draft (draft)
  2. Pending (pending)
  3. Published (publish)
  4. Expired (expired)

In this example we want to send an alert out when a published job expires, so the post status transition hook will be called publish_to_expired. WordPress automatically triggers this hook when necessary.

The hook/code will look like this:

When the hook is triggered, the expired_post method will be called and passed a post object (the post which has had it’s status modified).

Check the post object

We must remember, this hook can be triggered by any post, not just a job. Let’s check it’s type:

Create your email alert content

We’ve got a trigger now, which also passes the post. Now we can use this to create the actual alert email, and send it using wp_mail.

Content wise, lets have this read:

Hello,

The job “{job_title}” which you posted on {sitename} has just expired and will no longer be visible.

To check your other active listings, or post a new job listing, please visit your dashboard.

Putting this into the code we’ll have this:

Get the email address to notify

Two outcomes here; we can either send to the registered user, or the application email. If the user is a guest and provided neither, we can send nothing.

This code gets the application email (if set) from the listing, or if it’s not a guest submission, the user email.

Send it

Now we just need to send the email. wp_mail makes this simple.

All together now

Here is the final code combined and ready to go:

And here is what you’ll receive:

2013-12-24 at 17.44