WordPress: Bootstrap Alert Shortcode

Do you want to add bootstrap alerts to your blog?
Here is how to do it!

The Code

Add the following code to your functions.php.
Aside of bootstrap I use fontawesome icons for the alerts.

 * Shorcode function for creating bootsrap alerts.
 * @param type either one of "default", "primary", ""secondary" "info", "success", 
 *                           "warning" or "danger" 
 * @param title optional title for the alert
 * @param icon optional custom fontawesome icon for the alert
function my_alert($atts, $content) { 
	$attributes = shortcode_atts( array(
		'type' => 'info',
		'title' => '',
		'icon' => '',
	), $atts );
	// Resolve Icon
	$icon = $attributes['icon'];
	if($attributes['icon'] == ''){
			case "info": 		$icon = 'info-circle';				break;
			case "danger": 		$icon = 'exclamation-circle';		break;
			case "warning": 	$icon = 'exclamation-triangle';		break;
			case "success": 	$icon = 'check-circle';				break;
			default: '';
	// Build Alert HTML
	$result = '<div class="alert alert-' . $attributes['type'] . ' flex-row-nowrap flex-align-center" role="alert">';
		if($icon != ''){
			$result .= '<i class="fa fa-' . $icon . '"></i>' . "\n";
		$result .= '<span class="flex-item-grow ml-2">';
			if($attributes['title'] != ''){
				$result .= '<strong>' . $attributes['title'] . '</strong><br>' . "\n";
		$result .= $content . '</span>' . "\n";
	$result .= ' </div>' . "\n";

	return $result;
add_shortcode( 'alert', 'my_alert' );

Shortcode Usage

The shortcode can be used like this:

[alert type="info"]This is a info alert![/alert]
[alert type="info" title="With title"]This is a info alert with title![/alert]
[alert type="warning"]This is a warning alert![/alert]
[alert type="danger"]This is a danger alert![/alert]
[alert type="success"]This is a success alert![/alert]
[alert type="primary" title="With title no icon"]This is a primary alert![/alert]
[alert type="secondary" title="With title an custom icon" icon="envelope"]This is a secondary alert![/alert]

Example Alerts

Here what it looks like when above shortcode examples get rendered:



Leave a Reply

Your email address will not be published.