Learn how to build a reusable helper function that generates internal and external buttons dynamically with proper URL handling and target attributes.
/* set the link group function*/
function button_group($button = null, $class = null){
$target = false;
$link = "";
if(empty($button))
{
return;
}
$internal_link = $button['button_internal_link'];
$external_link = $button['button_external_link'];
$link_type = $button['button_link'];
$button_label = $button['button_label'];
if($link_type == 'button_internal_link' && !empty($internal_link)){
$link = $internal_link;
}elseif ($link_type == 'button_external_link' && !empty($external_link)) {
$target = true;
$link = $external_link;
}
if(empty($button_label) OR empty($link))
{
return;
}
$href_link = null;
if(!empty($link) && $link != null)
{
if($link == '#' )
{
$href_link = $link;
$target = '';
}
else
{
$url = trim($link);
if (!preg_match("~^(?:f|ht)tps?://~i", $url))
{
$href_link= "http://" . $url;
}
else
{
$href_link = trim($link);
}
}
}
if ($class != ''){
$class = 'class="'.$class.'"';
}
if ($target == true)
{
return '<a '.$class.' href="'.$href_link.'" target="_blank" rel="noopener">'.$button_label.'</a>';
}
else
{
return '<a '.$class.' href="'.$href_link.'">'.$button_label.'</a>';
}
}