Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danstramer/6a22b0b4feb66d5787b05efe7e77c6c2 to your computer and use it in GitHub Desktop.
Save danstramer/6a22b0b4feb66d5787b05efe7e77c6c2 to your computer and use it in GitHub Desktop.
Create s shortcode button with attributes
//https://www.wpexplorer.com/wordpress-button-shortcode/
//[button url="YOUR LINK" target="self" color="blue"]Button Text[/button]
//[button url="YOUR LINK" target="self" text="Button Text"]
function myprefix_button_shortcode( $atts, $content = null ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'url' => '',
'title' => '',
'target' => '',
'text' => '',
'color' => '',
), $atts ) );
// Use text value for items without content
$content = $text ? $text : $content;
// Return button with link
if ( $url ) {
$link_attr = array(
'href' => esc_url( $url ),
'title' => esc_attr( $title ),
'target' => ( 'blank' == $target ) ? '_blank' : '',
'class' => 'btn shortcode-btn color-' . esc_attr( $color ),
);
$link_attrs_str = '';
foreach ( $link_attr as $key => $val ) {
if ( $val ) {
$link_attrs_str .= ' ' . $key . '="' . $val . '"';
}
}
return '<a' . $link_attrs_str . '><span>' . do_shortcode( $content ) . '</span></a>';
}
// No link defined so return button as a span
else {
return '<span class="myprefix-button"><span>' . do_shortcode( $content ) . '</span></span>';
}
}
add_shortcode( 'button', 'myprefix_button_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment