Add WP style shortcodes support to emails

Also pass shortcode arguments to custom shortcode functions

[MAILPOET-3465]
This commit is contained in:
wxa
2021-03-22 08:22:05 +03:00
committed by Veljko V
parent 4116a0f3da
commit 4ea2337814
3 changed files with 49 additions and 0 deletions

View File

@ -80,19 +80,60 @@ class Shortcodes {
false;
}
/**
* Parse a MailPoet-style shortcode.
* The syntax is [category:action | argument:argument_value], it can have a single argument.
*/
public function match($shortcode) {
preg_match(
'/\[(?P<category>\w+)?:(?P<action>\w+)(?:.*?\|.*?(?P<argument>\w+):(?P<argument_value>.*?))?\]/',
$shortcode,
$match
);
// If argument exists, copy it to the arguments array
if (!empty($match['argument'])) {
$match['arguments'] = [$match['argument'] => isset($match['argument_value']) ? $match['argument_value'] : ''];
}
return $match;
}
/**
* Parse a WordPress-style shortcode.
* The syntax is [category:action arg1="value1" arg2="value2"], it can have multiple arguments.
*/
public function matchWPShortcode($shortcode) {
$atts = WPFunctions::get()->shortcodeParseAtts(trim($shortcode, '[]/'));
if (empty($atts[0])) {
return [];
}
$shortcodeName = $atts[0];
list($category, $action) = explode(':', $shortcodeName);
$shortcodeDetails = [];
$shortcodeDetails['category'] = $category;
$shortcodeDetails['action'] = $action;
$shortcodeDetails['arguments'] = [];
foreach ($atts as $attrName => $attrValue) {
if (is_numeric($attrName)) {
continue; // Skip unnamed attributes
}
$shortcodeDetails['arguments'][$attrName] = $attrValue;
// Make a shortcut to the first argument
if (!isset($shortcodeDetails['argument'])) {
$shortcodeDetails['argument'] = $attrName;
$shortcodeDetails['argument_value'] = $attrValue;
}
}
return $shortcodeDetails;
}
public function process($shortcodes, $content = '') {
$processedShortcodes = [];
foreach ($shortcodes as $shortcode) {
$shortcodeDetails = $this->match($shortcode);
if (empty($shortcodeDetails)) {
// Wrong MailPoet shortcode syntax, try to parse as a native WP shortcode
$shortcodeDetails = $this->matchWPShortcode($shortcode);
}
$shortcodeDetails['shortcode'] = $shortcode;
$shortcodeDetails['category'] = !empty($shortcodeDetails['category']) ?
$shortcodeDetails['category'] :
@ -106,6 +147,8 @@ class Shortcodes {
$shortcodeDetails['action_argument_value'] = !empty($shortcodeDetails['argument_value']) ?
$shortcodeDetails['argument_value'] :
false;
$shortcodeDetails['arguments'] = !empty($shortcodeDetails['arguments']) ?
$shortcodeDetails['arguments'] : [];
$category = strtolower($shortcodeDetails['category']);
$categoryClass = $this->getCategoryObject($category);
@ -126,6 +169,7 @@ class Shortcodes {
$this->subscriber,
$this->queue,
$content,
$shortcodeDetails['arguments'],
$this->wpUserPreview
);
$processedShortcodes[] = ($customShortcode === $shortcode) ?