Register an additional email service

Register an additional SendGrid email service that uses a custom API key when the contact is unconfirmed and the email type is marketing.

Add this code to your theme's functions.php file or use a code snippets plugin.

<?php

add_filter( 'pre_option_gh_marketing_email_service', 'filter_gh_marketing_email_service' );

/**
 * Short circuit get_option() for the marketing email service to return a custom on instead
 *
 * @return string
 */
function filter_gh_marketing_email_service( $pre_option ) {

	// Get the current email being sent
	$email = \Groundhogg\the_email();

	// Not an email we're worried about
	if ( ! $email ){
		return $pre_option;
	}

	// Get the current contact
	$contact = $email->get_contact();

	// If the contact is unconfirmed
	if ( $contact->optin_status_is( \Groundhogg\Preferences::UNCONFIRMED ) ){
		return 'my_custom_service';
	}

	return $pre_option;
}

add_action( 'groundhogg/loaded', 'register_custom_email_service' );

/**
 * Register the custom SendGrid service
 *
 * @return void
 */
function register_custom_email_service() {
	Groundhogg_Email_Services::register( 'my_custom_service', 'SendGrid Custom', 'custom_sendgrid_service_callback' );
}

define( 'CUSTOM_SENGRID_API_KEY', 'abcd12345' );

/**
 * This is a wrapper function which swaps out the API key with one for an additional account.
 *
 * @return bool
 */
function custom_sendgrid_service_callback( $to, $subject, $message, $headers = '', $attachments = array() ) {

	if ( ! function_exists( 'sendgrid_mail' ) ){
		return false;
	}

	// Set the API key to the new custom account
	\GroundhoggSendGrid\SendGrid\SendGrid::set_api_key( CUSTOM_SENGRID_API_KEY );

	$result = sendgrid_mail( $to, $subject, $message, $headers, $attachments );

	// Setting the key to null will prompt the API to fetch the key from the settings for the next email
	\GroundhoggSendGrid\SendGrid\SendGrid::set_api_key( null );

	return $result;
}
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us