Skip to content

Instantly share code, notes, and snippets.

@taotiwordpress
Last active September 22, 2021 16:34
Show Gist options
  • Save taotiwordpress/ec8a68b382edaf281691658c6eebc14d to your computer and use it in GitHub Desktop.
Save taotiwordpress/ec8a68b382edaf281691658c6eebc14d to your computer and use it in GitHub Desktop.
[button shortcode] #php #wysiwyg #shortcode
<?php
/**
* Custom ShortCode for WYSIWYG Buttons.
*
* @todo Convert to allow for <button> and identifying the need for role='button'.
*/
function custom_button_shortcode( $atts, $content = null ) {
// shortcode attributes
$atts = shortcode_atts(
array(
'class' => 'blue-gradient-new', // Default button variant goes here. If none, leave blank.
'url' => '',
'title' => '',
'target' => '',
'text' => '',
),
$atts,
'custombutton',
);
$content = $text ? $text : $content;
// Returns the button with a link
if ( isset( $atts['url'] ) ) {
$link_attr = array(
'href' => esc_url( $atts['url'] ),
'title' => esc_attr( $atts['title'] ),
'target' => ( 'blank' === $atts['target'] ) ? '_blank' : '',
);
$link_attrs_str = '';
foreach ( $link_attr as $key => $val ) {
if ( $val ) {
$link_attrs_str .= ' ' . $key . '="' . $val . '"';
}
}
/**
* Generate the 'button'.
*
* Note: The 'button' class is already being added.
*/
$custom_button_link = '<a' . $link_attrs_str . '><span class="button ' . esc_attr( $atts['class'] ) . '">' . do_shortcode( $content ) . '</span></a>';
return $custom_button_link;
} else {
/**
* Return as span when no link defined
*/
return '<span class="' . esc_attr( $atts['class'] ) . '"><span>' . do_shortcode( $content ) . '</span></span>';
}
}
add_shortcode( 'custombutton', 'custom_button_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment