Simple button with various uses.
<?php
/*
Use cases:
[button href="/contact" text="contact us"]
[button href="/contact" text="contact us" /]
[button href="/contact"]Contact Us[/button]
[button]<a href="/contact/">Contact Us</a>[/button]
Available shortcode attributes
id, class, style, href, target, rel, text
*/
function shortcode_the_d4_button( $atts, $content = NULL ) {
$attributes = array(
'id' => NULL,
'class' => NULL,
'style' => NULL,
'href' => NULL,
'target' => NULL,
'rel' => NULL,
);
// Shortcode attributes
$shortcode_attributes = array(
'text' => 'Click Here',
);
$attr = shortcode_atts( array_merge($attributes, $shortcode_attributes), $atts );
// Build Link Attributes
$attr['class'] = 'button ' . $attr['class'];
$link_attributes = '';
foreach ( $attributes as $key => $value ) {
if ( isset($attr[$key]) ) {
$link_attributes .= ' ' . $key . '="' . trim($attr[$key]) . '"';
}
}
// BUILD OUTPUT
$output = '';
// Wrapping a link
if ( isset($content) && ! empty($content) ) {
// Content likely contains an <a> tag
if ( strpos($content, '<a ') !== false ) {
$content = str_replace('<a ', '<a' . $link_attributes, $content);
$output .= $content;
} else {
$output .= '<a' . $link_attributes . '>';
$output .= $content;
$output .= '</a>';
}
// No wrapper
} else {
$output .= '<a' . $link_attributes . '>';
$output .= $attr['text'];
$output .= '</a>';
}
return $output;
} add_shortcode('button', 'shortcode_the_d4_button');