Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

How to use WP_Cron to send email notifications based on custom events

WP_Cron gives WordPress a built-in way to run work after a site event instead of holding up the request that detected it. When a WooCommerce order becomes ready for packing, a membership activates, or a document is approved, a plugin can capture that event and schedule an email for later. The reliable pattern separates detection, scheduling, delivery, and logging.

WP_Cron is request-driven rather than a true background clock. WordPress checks for due jobs when it receives traffic, so a busy store may process a job quickly while a quiet site can wait. That is often acceptable for notifications, but it does not guarantee a precise delivery minute. A system scheduler or WooCommerce Action Scheduler is better when timing is critical.

Many Australian stores sell in Australian dollars, include 10% GST, and use .com.au domains, while some keep WordPress hosting in Sydney or Melbourne. Their support teams may span Perth, Brisbane, Sydney, and Melbourne, so “9 am local” is ambiguous unless the timezone is named. Cron timestamps, meanwhile, should remain in UTC.

A dependable implementation also treats email as a separate delivery system. Use an authenticated SMTP service, configure SPF, DKIM, and DMARC for the sending domain, and keep marketing consent separate from genuine order or account messages. Under Australia’s Spam Act 2003, commercial messages generally require consent, clear sender identification, and a functional unsubscribe; transactional messages should remain clearly related to the customer’s order or account.

Mechanism Best suited for When it runs Reliability Main trade-off
WP-Cron Lightweight notifications on a WordPress site During incoming requests Good on busy sites Can be delayed when traffic is low
System cron Precise, recurring WordPress jobs At fixed intervals High when configured correctly Needs server or host-panel access
Action Scheduler WooCommerce jobs, queues, and retries Through its queue runner Strong for Woo workflows More moving parts than plain WP-Cron
Immediate request Confirmation of a user action During that request Fast at first glance Timeouts and repeat clicks can cause failures or duplicates

Map the event before writing the mailer

A custom event should describe a completed business fact, not a button click. “Order ready for packing” is useful because it can come from an order hook, an admin action, or an integration. “Admin clicked Send” is not durable: a failed request can leave the site unsure whether the work happened.

Give each event a stable name and small payload. The contract should identify required arguments, the source of the recipient, and the record that proves the notification was handled. Pass identifiers rather than names, email addresses, or large objects; sensitive values can be fetched again when the job runs and should not sit in WordPress cron options.

This WooCommerce example turns a vendor hook into an application event. The event key is deterministic, so a repeated status callback produces the same key:

add_action(
	'woocommerce_order_status_processing',
	'acme_emit_order_ready',
	10,
	1
);

function acme_emit_order_ready( $order_id ) {
	$event_key = 'order-ready-' . absint( $order_id );

	do_action( 'acme_order_ready', absint( $order_id ), $event_key );
}

Schedule a single custom action

Register the scheduler when the business event fires, not on every page load. A short delay stops outgoing mail from competing with the request and gives buffered records time to settle:

add_action( 'acme_order_ready', 'acme_schedule_order_email', 10, 2 );

function acme_schedule_order_email( $order_id, $event_key ) {
	$args = array( absint( $order_id ), sanitize_key( $event_key ) );

	if ( wp_next_scheduled( 'acme_send_order_email', $args ) ) {
		return;
	}

	wp_schedule_single_event(
		time() + ( 5 * MINUTE_IN_SECONDS ),
		'acme_send_order_email',
		$args
	);
}

add_action( 'acme_send_order_email', 'acme_handle_order_email', 10, 2 );

For recurring work, use wp_schedule_event() and create it during plugin activation or another controlled process. Avoid placing this call in a template or front-end callback, where every visit could compete to create the job.

if ( ! wp_next_scheduled( 'acme_inventory_check' ) ) {
	wp_schedule_event(
		time() + HOUR_IN_SECONDS,
		'hourly',
		'acme_inventory_check'
	);
}

wp_next_scheduled() matches both the hook and its arguments, so keep the payload consistent. Critical jobs should not depend on a visitor arriving: configure server cron to invoke WP-CLI every few minutes, or use Action Scheduler. WordPress stores jobs in its cron option, making them persistent across requests but still dependent on a trigger.

Build a safe email handler

In the handler, load the order again and derive the recipient from trusted server-side data. Never accept an email address directly from a browser or from unvalidated cron data:

function acme_handle_order_email( $order_id, $event_key ) {
	$order = wc_get_order( $order_id );

	if ( ! $order ) {
		return;
	}

	$email = sanitize_email( $order->get_billing_email() );

	if ( ! is_email( $email ) ) {
		return;
	}

	$total = 'AUD ' . number_format(
		(float) $order->get_total(),
		2,
		'.',
		','
	);

	$subject = sprintf(
		'Order %s is ready for packing',
		$order->get_order_number()
	);

	$body = sprintf(
		"Hello,\n\nOrder %s is ready for packing.\n\nTotal: %s\nDetails: %s\n",
		$order->get_order_number(),
		$total,
		$order->get_view_order_url()
	);

	$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
	$sent    = wp_mail( $email, $subject, $body, $headers );

	if ( ! $sent ) {
		do_action( 'acme_notification_failed', $order_id, $event_key );
	}
}

A successful wp_mail() call means the configured mail layer accepted the message, not that the inbox received it. Send through authenticated SMTP, use a From address on your own domain, and point Reply-To at a monitored support mailbox. A .com.au sending domain still needs correct SPF, DKIM, and DMARC records.

Plain text is a safe default for transactional notices. If HTML is required, escape each field and pass allowed markup through wp_kses_post(). Australian users generally appreciate direct, friendly wording: “Your order is ready for packing” communicates the action, while playful slang such as “no worries, all sorted” can leave important details unclear.

Prevent duplicates and retry failures

Delivery can be attempted twice when WooCommerce repeats a hook, two requests overlap, or a timeout occurs after the mail provider accepted a message. Use the event key as an idempotency key and claim it before sending:

$claim_key = '_acme_claim_' . md5( $event_key );

if ( ! add_post_meta( $order_id, $claim_key, '1', true ) ) {
	return;
}

$sent = wp_mail( $email, $subject, $body, $headers );

if ( $sent ) {
	update_post_meta(
		$order_id,
		'_acme_result_' . md5( $event_key ),
		'sent'
	);
} else {
	delete_post_meta( $order_id, $claim_key );
	do_action( 'acme_notification_failed', $order_id, $event_key );
}

Post meta provides a practical claim for a WordPress implementation. Keep the claim value unchanged so the unique key remains effective, and record the result separately. This blocks normal repeat delivery; a high-contention workflow needs a database-enforced unique row or a scheduler lock.

Exactly-once email is not realistic across an SMTP boundary: a process can crash after the provider accepts the message but before WordPress records success. Include the event key in logs, cap retries, and have a rare duplicate investigated rather than weakening every check. Action Scheduler is a strong choice when WooCommerce already manages queues, retries, and action logs.

Handle Australian timezones correctly

Store event times as Unix timestamps in UTC and convert them only for display. WordPress can apply a named timezone without the fragile manual offsets used for daylight saving:

$utc_timestamp = current_time( 'timestamp', true );
$local_time    = wp_date(
	'j F Y, g:i a',
	$utc_timestamp,
	new DateTimeZone( 'Australia/Brisbane' )
);

Use IANA names such as Australia/Sydney, Australia/Brisbane, Australia/Adelaide, and Australia/Perth. Sydney and Melbourne move between AEST and AEDT; Brisbane stays on AEST; Adelaide uses ACST or ACDT; Perth remains on AWST. A fixed “plus ten hours” rule will be wrong during the transition.

Schedule a Brisbane pickup message against Australia/Brisbane, then render it in the customer’s selected zone. If a 4 pm Brisbane event reaches Sydney after that office has finished for the arvo, the timestamp is still correct but the communication timing is poor. Resolve the intended local time first, convert it to UTC, and only then create the cron event.

Test the event without waiting for traffic

Test on staging where real recipients and real mail are disabled. Trigger the event directly, inspect the scheduled arguments, then run due jobs with WP-CLI:

do_action( 'acme_order_ready', 123, 'order-ready-123' );
wp cron event list --fields=hook,next_run_gmt,recurrence
wp cron event run acme_send_order_email --force

A pre_wp_mail filter can capture outgoing messages during functional tests. Exercise a repeated event, an unknown order, a missing address, an SMTP outage, the daylight-saving boundary, and a low-traffic period. Check that failures are logged without placing message content or customer addresses in the log.

After deployment, combine these checks with web regression checks around checkout and account pages, because an email workflow can pass while the surrounding site still regresses. Re-run the notification flow after plugin updates, WooCommerce upgrades, or a change to the WordPress timezone setting.

Operate the scheduler through a controlled rollout

For predictable timing, give WordPress a server-level trigger. A common crontab entry runs every five minutes; replace the path and user with those of the installation:

*/5 * * * * cd /srv/wordpress && wp cron event run --due-now --quiet

Only disable WordPress’s built-in trigger after the external runner is working. Some managed Australian hosts restrict the loopback request used by WordPress’s own trigger, so verify the chosen runner and WP-CLI permissions. Use wp cron event list to find overdue jobs, log each attempt, alert on an old “last success” time, and clear obsolete recurring work with wp_clear_scheduled_hook() during plugin removal.

A controlled rollout keeps these operational controls in place:

With a defined event contract, idempotent handler, timezone-safe timestamps, authenticated delivery, and an external trigger, WordPress can send dependable custom notifications without tying the workflow to a particular page visit.