Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Created May 19, 2020 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/b7788da6b277df585048fdd8e220c45b to your computer and use it in GitHub Desktop.
Save nfsarmento/b7788da6b277df585048fdd8e220c45b to your computer and use it in GitHub Desktop.
WordPress shortcode to show button
<?php
/**
*
* Add a new custom button.
* Usage [custombutton url="https://www.nuno-sarmento.com/" target="self" text="Go To NS"].
*/
// @codingStandardsIgnoreStart
function ns_custom_button_shortcode( $atts, $content = null ) {
// shortcode attributes
extract( shortcode_atts( array(
'url' => '',
'title' => '',
'target' => '',
'text' => '',
), $atts ) );
$content = $text ? $text : $content;
// Returns the button with a link
if ( $url ) {
$link_attr = array(
'href' => esc_url( $url ),
'title' => esc_attr( $title ),
'target' => ( 'blank' == $target ) ? '_blank' : '',
'class' => 'custombutton'
);
$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>';
}
// Return as span when no link defined
else {
return '<span class="custombutton"><span>' . do_shortcode( $content ) . '</span></span>';
}
}
add_shortcode( 'custombutton', 'ns_custom_button_shortcode' );
// @codingStandardsIgnoreEnd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment