Emails

In HivePress, emails are implemented as PHP classes with specific properties, such as the email subject and message with replaceable tokens. For example, the user registration email is implemented as a User_Register class, with a subject and message that contains a %user_name% token, replaced with a unique user name for each registration.

Creating emails

If you are developing a HivePress extension that requires custom email notifications, you should create a new email. To do this, create a new class-{email-name}.php file (use lowercase letters, numbers, and hyphens only) in the includes/emails extension subdirectory and HivePress will load it automatically.

Then, define the email PHP class. The class name should be based on the file name but with underscores instead of hyphens and no lowercase restriction (e.g. Foo_Bar class for the class-foo-bar.php file). Pick a name that is unique enough to avoid conflicts with other HivePress emails.

<?php
namespace HivePress\Emails;

use HivePress\Helpers as hp;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

class Foo_Bar extends Email {
	public function __construct( $args = [] ) {

		// Set the default subject and message.
		$args = hp\merge_arrays(
			[
				'subject' => 'Custom subject',
				'body'    => 'Custom message with a %custom_token%.',
			],
			$args
		);

		parent::__construct( $args );
	}

	public static function init( $meta = [] ) {

		// Add details for the email editor.
		$meta = hp\merge_arrays(
			[
				'label' => 'My Custom Email',
			],
			$meta
		);

		parent::init( $meta );
	}
}

The code example above defines a new Foo_Bar email with the default subject and message with a replaceable token. It also has a label set in the init method, which means that this email is available for editing in the HivePress > Emails section.

Sending emails

To send an email, create its class object with the following parameters:

  • recipient - the recipient's email address;

  • headers - an optional array of email headers;

  • tokens - an array of tokens to replace in the email.

Then, call the send method. For example, the code below sends the Foo_Bar email to the user@example.com address, replacing the %custom_token% in its content with "123".

( new HivePress\Emails\Foo_Bar(
	[
		'recipient' => 'user@example.com',

		'tokens'    => [
			'custom_token' => 123,
		],
	]
) )->send();

Customizing emails

You can customize any of the available HivePress emails via the hivepress/v1/emails/{email_name} filter hook. For example, the code below changes the user registration email subject:

add_filter(
	'hivepress/v1/emails/user_register',
	function( $email ) {
		$email['subject'] = 'Custom subject';

		return $email;
	}
);

Last updated