How to add attributes to a shortcode

You just have to add another element to the array (and then output it):

function btn_shortcode( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'class' => 'button',
        'href'  =>  '#'
    ), $atts );

    return '<a class="' . esc_attr($a['class']) . '" href="' . esc_attr($a['href']) . '">' . $content . '</a>';
}
add_shortcode( 'button', 'btn_shortcode' );

//EDIT:

In order to add user-defined styles you also just have to add another element to the array:

function btn_shortcode( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'class' => 'button',
        'href'  =>  '#',
        'style' =>  ''
    ), $atts );

    return '<a class="' . esc_attr($a['class']) . '" href="' . esc_attr($a['href']) . '" style="' . esc_attr($a['style']) . '">' . $content . '</a>';
}
add_shortcode( 'button', 'btn_shortcode' );

Here’s a usage example:

[button href="https://wordpress.stackexchange.com/questions/232197/foo" class="btn btn-lg btn-default" style="font-weight:bold; margin-top:50px; background-color: #999"]Learn More[/button]

//EDIT2:

You can add different style attributes to the shortcode and then output them all inside the style attribute of the HTML tag, but this will limit the custom CSS only to these predefined attributes and you also must have some predefined values for each of them in case the user leaves them empty.
If some of them are left empty and you have no predefined values you might end up with something like this – <a href="#foo" class="button" style="font-weight:; margin-top: 20px; background-color:;"

function btn_shortcode( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'class' => 'button',
        'href'  =>  '#',
        'background-color' =>  '#999',
        'font-weight' => 'normal',
        'margin-top' => '10px'

    ), $atts );

    return '<a class="' . esc_attr($a['class']) . '" href="' . esc_attr($a['href']) . '" style="font-weight:' . esc_attr($a['font-weight']) . '; background-color' . esc_attr($a['background-color']). '; margin-top:' . esc_attr($a['margin-top']) . ';">' . $content . '</a>';
}

Here’s a usage example:

[button href="https://wordpress.stackexchange.com/questions/232197/foo" class="btn btn-lg btn-default" font-weight="bold" margin-top="50px" background-color="#999"]Learn More[/button]

Leave a Comment