I need to allow users to use a shortcode [warning]
in the frontend of my site. This shortcode may be followed by only one [warning](arg1)
or two arguments [warning](optional-arg)(arg1)
.When the two arguments are entered the first one optional-arg
will be considered as the heading and the second arg1
as the body text and if only one is entered arg1
it will be considered as the body text.
Here is the code I'm managing
function warning($text) {
$text = preg_replace('/\[warning\]\s*\((.*?)\)/', '<div class="alert alert-error"><div class="alert-content"> $1 </div></div>', $text); //for warning with body text only
$text = preg_replace('/\[warning\]\s*\((.*?)\)\s*\((.*?)\)/', '<div class="alert alert-error"><div class="alert-content"><h2 class="alert-title"> $1 </h2><div class="alert-body"><p> $2 </p></div></div></div>', $text); //for warning with heading
return $text;
}
add_filter('the_content', 'warning');
add_filter( 'the_excerpt', 'warning');
The problem is that the second argument is not considered and is out of the warning box.
This is a job for preg_replace_callback
Output: