WooCommerce

Yaymail WooCommerce邮件模板生成器,支持自定义模版

Yaymail是一个WooCommerce Email Page Builder,用现成的组件和拖拽的方式快速拼搭出一个邮件模板。它基于vue.js和shortcode方式工作,在众多的邮件定制插件中,它是我发先的唯一一个支持WooCommerce自定义邮件的插件,虽然你需要写一些代码来使它兼容你自己的模板。

这篇笔记是基于WooCommerce 创建自定义邮件

yaymail woocommerce solablog
Yaymail WooCommerce Email模板生成器

创建Yaymail Addon的思路

addon要以插件的形式存在,最简单的addon至少包含两个文件:

  • 插件主文件,用于注册你要支持的模板,定义自己模板中用到的shortcode等等.
  • 邮件的默认模板,由于yaymail的模板要覆盖掉邮件原本的模板,所以要有一个初始的样子,比如标题、文字、订单格式等内容。当用户使用reset功能重置模板时,就会使用这个默认的样子。

插件的结构如下所示:

📦yaymail-addon-custom-email
 ┣ 📂views
 ┃ ┗ 📂templateDefault
 ┃ ┃ ┗ 📜DefaultCustomEmail.php
 ┗ 📜yaymail-addon-custom-email.php

最终效果如下:

solagirl.net: yaymail woocommerce支持custom email

插件代码

点击这里下载源代码

插件主文件

yaymail-addon-custom-email.php是主文件,大体思路如下:

  1. 插件header,写插件必备
  2. namespace YayMailCustomEmail;生命php命名空间,不能省略。在定义function时名字里必须含有namespace,否则插件可能停止工作。
  3. spl_autoload_register()注册一个自动加载类的方法。
  4. 让你的addon插件在WordPress插件列表页显示一些额外信息,比如一个Start Customizing链接和文档链接。再添加一个admin notice,提示用户使用这个插件必须先安装yaymail。这些内容所有yaymail的扩展都一样,照搬即可。
  5. 通过action yaymail_before_enqueue_dependence加载用到的css和js文件,最简单的扩展用不着这些,所以我注释掉了。
  6. 通过filter yaymail_plugins注册你的自定义邮件。需要更改plugin_nametemplate_name
  7. 如果你的邮件有特殊功能,可以用shortcode实现,那么你需要:1)将shortcode名称添加到编辑器的shortcode列表里(yaymail_list_shortcodes);2)传递一些参数给shortcode(yaymail_shortcodes);3)定义shortcode的输出(yaymail_do_shortcode)。
  8. 如果你的shortcode输出比较复杂,用单独的function来编写输出。

yaymail-addon-custom-email.php的内容如下:

<?php

/**
 * Plugin Name: YayMail Addon for Custom Email
 * Plugin URI: https://www.solagirl.net
 * Description: An example of how to make write YayMail extention.
 * Version: 1.0
 * Author: Sola
 * Author URI: https://www.solagirl.net
 * Text Domain: yaymail
 * WC requires at least: 3.0.0
 * WC tested up to: 6.0.2
 * Domain Path: /i18n/languages/
 */

namespace YayMailCustomEmail;

defined('ABSPATH') || exit;

spl_autoload_register(
	function ($class) {
		$prefix   = __NAMESPACE__;
		$base_dir = __DIR__ . '/views';

		$len = strlen($prefix);
		if (strncmp($prefix, $class, $len) !== 0) {
			return;
		}

		$relative_class_name = substr($class, $len);

		$file = $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';

		if (file_exists($file)) {
			require $file;
		}
	}
);

// Add action link customize
add_filter('plugin_action_links_' . plugin_basename(__FILE__),  __NAMESPACE__ . '\\yaymail_addon_add_action_links');
function yaymail_addon_add_action_links($actions) {

	if (defined('YAYMAIL_PREFIX')) {
		$links   = array(
			'<a href="' . admin_url('admin.php?page=yaymail-settings') . '" aria-label="' . esc_attr__('View WooCommerce Email Builder', 'yaymail') . '">' . esc_html__('Start Customizing', 'yaymail') . '</a>',
		);
		$actions = array_merge($links, $actions);
	}
	return $actions;
}

// Add action link docs and support
add_filter('plugin_row_meta', __NAMESPACE__ . '\\yaymail_addon_custom_plugin_row_meta', 10, 2);
function yaymail_addon_custom_plugin_row_meta($plugin_meta, $plugin_file) {

	if (strpos($plugin_file, plugin_basename(__FILE__)) !== false) {
		$new_links = array(
			'docs'    => '<a href="https://yaycommerce.gitbook.io/yaymail/" aria-label="' . esc_attr__('View YayMail documentation', 'yaymail') . '">' . esc_html__('Docs', 'yaymail') . '</a>',
			'support' => '<a href="https://yaycommerce.com/support/" aria-label="' . esc_attr__('Visit community forums', 'yaymail') . '">' . esc_html__('Support', 'yaymail') . '</a>',
		);

		$plugin_meta = array_merge($plugin_meta, $new_links);
	}

	return $plugin_meta;
}

// Add action notice
add_action('after_plugin_row_' . plugin_basename(__FILE__), __NAMESPACE__ . '\\yaymail_addon_add_notification_after_plugin_row', 10, 2);
function yaymail_addon_add_notification_after_plugin_row($plugin_file, $plugin_data) {

	if (!defined('YAYMAIL_PREFIX')) {
		$wp_list_table = _get_list_table('WP_MS_Themes_List_Table');
?>
		<script>
			var plugin_row_element = document.querySelector('tr[data-plugin="<?php echo esc_js(plugin_basename(__FILE__)); ?>"]');
			plugin_row_element.classList.add('update');
		</script>
	<?php
		echo '<tr class="plugin-update-tr' . (is_plugin_active($plugin_file) ? ' active' : '') . '"><td colspan="' . esc_attr($wp_list_table->get_column_count()) . '" class="plugin-update colspanchange" >';
		echo '<div class="notice inline notice-warning notice-alt"><p>';
		echo esc_html__('To use this addon, you need to install and activate YayMail plugin. Get ', 'yaymail') . '<a href="' . esc_url('https://wordpress.org/plugins/yaymail/') . '">' . esc_html__('YayMail Free', 'yaymail') . '</a> or <a href="' . esc_url('https://yaycommerce.com/yaymail-woocommerce-email-customizer/') . '">' . esc_html__('YayMail Pro', 'yaymail') . '</a>.
					</p>
				</div>
			</td>
			</tr>';
	}
}

function yaymail_subscription_dependence() {
	wp_enqueue_script('yaymail-subscription', plugin_dir_url(__FILE__) . 'assets/dist/js/app.js', array(), YAYMAIL_VERSION, true);
	wp_enqueue_style('yaymail-subscription', plugin_dir_url(__FILE__) . 'assets/dist/css/app.css', array(), YAYMAIL_VERSION);
}
//add_action( 'yaymail_before_enqueue_dependence', __NAMESPACE__ . '\\\yaymail_custom_email_dependence' );

// Register your custom email
function yaymail_register_email_template($plugins) {
	$plugins[] = array(
		'plugin_name'      => 'Sola_WC_Custom_Email',
		'addon_components' => array(),
		'template_name'    => array('my_custom_email'),
	);
	return $plugins;
}
add_filter('yaymail_plugins', __NAMESPACE__ . '\\yaymail_register_email_template');

// Action create template default
add_filter('YaymailNewTempalteDefault', __NAMESPACE__ . '\\yaymail_new_template_default', 100, 3);
function yaymail_new_template_default($array, $key, $value) {
	if ('Sola_WC_Custom_Email' == $key) {
		$getHeading                   = $value->get_heading();
		$defaultCustomEmail = templateDefault\DefaultCustomEmail::getTemplates($value->id, $getHeading);
		return $defaultCustomEmail;
	}
	return $array;
}

/** SHORTCODE WILL DO HERE */

// Add shortcode to the list of shortcodes in the block editor
function yaymail_addon_custom_shortcode_attributes($shortcode_list) {
	$shortcode_list[] = array(
		'plugin' => 'Group Name',
		'shortcode' => array(
			['[yaymail_addon_custom_email_info]', 'my shortcode'],
		)
	);
	return $shortcode_list;
}
add_filter('yaymail_list_shortcodes', __NAMESPACE__ . '\\yaymail_addon_custom_shortcode_attributes');

// Call add_shortcode and pass some parameters
function yaymail_addon_add_shortcodes_to_list($shortcode_list) {
	$shortcode_list[] = 'yaymail_addon_custom_email_info';
	return $shortcode_list;
}
add_filter('yaymail_shortcodes', __NAMESPACE__ . '\\yaymail_addon_add_shortcodes_to_list');

// Create the replacement array to map shortcode to its content
function yaymail_addon_shortcode_callback_list($shortcode_list, $yaymail_informations, $args = array()) {
	$shortcode_list['[yaymail_addon_custom_email_info]'] = yaymail_addon_custom_email_info($yaymail_informations, $args);
	return $shortcode_list;
}
add_filter('yaymail_do_shortcode', __NAMESPACE__ . '\\yaymail_addon_shortcode_callback_list', 10, 3);

// Define the output of the custom shortcodes
function yaymail_addon_custom_email_info($yaymail_informations, $args) {

	ob_start();
	if (isset($yaymail_informations['order'])) : ?>
		<div>
			<hr>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
				tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
				quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
				consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
				cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
				proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
		</div>
	<?php else : ?>
		<h3>Demo content when sample order is selected</h3>
<?php
	endif;

	return ob_get_clean();
}

默认模板文件

默认模板文件DefaultCustomEmail.php,起作用是定义一个邮件的初始状态,给用户一个起点。如果编辑的不满意想重置,也会用到这个文件的内容。

DefaultCustomEmail.php的内容如下:

<?php

namespace YayMailCustomEmail\templateDefault;

defined( 'ABSPATH' ) || exit;

class DefaultCustomEmail {

	protected static $instance = null;

	public static function getInstance() {
		if ( null == self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public static function getTemplates( $customOrder, $emailHeading ) {
		$emailTitle        = __( $emailHeading, 'woocommerce' );
		$emailtext        = '<h2>Email Heading</h2>[yaymail_addon_custom_email_info]';

		// Elements
		$elements =
		'[{
			"id": "custom-email-logo",
			"type": "Logo",
			"nameElement": "Logo",
			"settingRow": {
				"backgroundColor": "#ECECEC",
				"align": "center",
				"pathImg": "",
				"paddingTop": "15",
				"paddingRight": "50",
				"paddingBottom": "15",
				"paddingLeft": "50",
				"width": "172",
				"url": "#"
			}
		}, {
			"id": "custom-email-title",
			"type": "ElementText",
			"nameElement": "Email Heading",
			"settingRow": {
				"content": "<h1 style=\"font-size: 30px; font-weight: 300; line-height: normal; margin: 0; color: inherit;\">' . $emailTitle . '</h1>",
				"backgroundColor": "#96588A",
				"textColor": "#ffffff",
				"family": "Helvetica,Roboto,Arial,sans-serif",
				"paddingTop": "36",
				"paddingRight": "24",
				"paddingBottom": "36",
				"paddingLeft": "24"
			}
		},{
			"id": "custom-email-text",
			"type": "ElementText",
			"nameElement": "Text",
			"settingRow": {
				"content": "' . $emailtext .' ",
				"backgroundColor": "#fff",
				"textColor": "#636363",
				"family": "Helvetica,Roboto,Arial,sans-serif",
				"paddingTop": "36",
				"paddingRight": "24",
				"paddingBottom": "36",
				"paddingLeft": "24"
			}
		},{
			"id": "custom-email-footer",
			"type": "ElementText",
			"nameElement": "Footer",
			"settingRow": {
				"content": "<p style=\"font-size: 14px;margin: 0px 0px 16px; text-align: center;\">[yaymail_site_name]&nbsp;- Built with <a style=\"color: #96588a; font-weight: normal; text-decoration: underline;\" href=\"https://woocommerce.com\" target=\"_blank\" rel=\"noopener\">WooCommerce</a></p>",
				"backgroundColor": "#ececec",
				"textColor": "#8a8a8a",
				"family": "Helvetica,Roboto,Arial,sans-serif",
				"paddingTop": "15",
				"paddingRight": "50",
				"paddingBottom": "15",
				"paddingLeft": "50"
			}
		}]';

		$templates = array(
			$customOrder => array(),
		);
		$templates[ $customOrder ]['elements'] = $elements;
		return $templates;
	}
}

注意$emailHeading是从woocommerce的邮件管理页面获取的标题,但yaymail并不支持woocommerce的订单号placeholder,可能会造成订单号不显示,想避免可以填写yaymail的订单号shortcode。