Wrap content in WooCommerce email template with PHP

/**
 * Wraps content in WooCommerce email template.
 *
 * @see https://wpcodebook.com/woocommerce-wrap-email-template-php/
 * @see https://github.com/woocommerce/woocommerce/blob/9.2.3/plugins/woocommerce/templates/emails/email-header.php
 * @see https://github.com/woocommerce/woocommerce/blob/9.2.3/plugins/woocommerce/templates/emails/email-footer.php
 * @see https://github.com/woocommerce/woocommerce/blob/9.2.3/plugins/woocommerce/includes/class-wc-emails.php#L290
 */
function wpcodebook_wrap_in_wc_email_template( $content, $email_heading = '' ) {

	// Header
	ob_start();
	wc_get_template( 'emails/email-header.php', array( 'email_heading' => $email_heading ) );
	$header = ob_get_clean();

	// Footer
	ob_start();
	wc_get_template( 'emails/email-footer.php' );
	$footer = ob_get_clean();
	// Footer placeholders
	$domain = wp_parse_url( home_url(), PHP_URL_HOST );
	$footer = str_replace(
		array(
			'{site_title}',
			'{site_address}',
			'{site_url}',
			'{woocommerce}',
			'{WooCommerce}',
		),
		array(
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
			$domain,
			$domain,
			'<a href="https://woocommerce.com">WooCommerce</a>',
			'<a href="https://woocommerce.com">WooCommerce</a>',
		),
		$footer
	);

	// Result
	return $header . $content . $footer;
}

Usage example:

wc_mail(
	get_option( 'admin_email' ),
	esc_html__( 'My awesome subject' ),
	wpcodebook_wrap_in_wc_email_template(
		esc_html__( 'My awesome content' ),
		esc_html__( 'My awesome heading' )
	)
);

Leave a Comment