Create a WordPress Button Shortcode With Changeable Class

Posted on January 28th, 2018 by M H in Tutorials | No Comments

Creating a WordPress button shortcode with changeable class and link

This is a pretty useful tutorial for all WordPress users. Being able to change your class and link is very handy especially when you like using different styles or need to add a different URL. Today I’ll show you how to do just that, and it’s very simple.

1.) Lets start by creating the function and add our shortcode, for this tutorial we’ve called ours [ button ].

function mhweb_button_styles( $atts, $content = null, $tag){

    //code goes here

}

add_shortcode( 'button', 'mhweb_button_styles');

2.) Now we add our array and add our shortcode tags

    extract( shortcode_atts( array(
       // extra classes
       'class' => '',
       'href' => '',
    ), $atts ) );

    if ( $class != '' )
       $class = ' ' . $class;
    if ( $href != '' )
       $href = ' ' . $href;
    $last = '';

    // check the shortcode tag to add a "last" class
    if ( strpos( $tag, '_last' ) !== false )        $tag = str_replace( '_last', ' last', $tag);

3.) Now add our output which will populate the button

    $output = '' . do_shortcode( $content ) . '';
    return $output;

We’re finished. Your following code should look like this:

function mhweb_button_styles( $atts, $content = null, $tag){

    extract( shortcode_atts( array(
       // extra classes
       'class' => '',
       'href' => '',
    ), $atts ) );

    if ( $class != '' )
       $class = ' ' . $class;
    if ( $href != '' )
       $href = ' ' . $href;
    $last = '';

    // check the shortcode tag to add a "last" class
    if ( strpos( $tag, '_last' ) !== false )        $tag = str_replace( '_last', ' last', $tag);

    $output = '' . do_shortcode( $content ) . '';
    return $output;
}
add_shortcode( 'button', 'mhweb_button_styles');

You’ve now created your shortcode. You can use it by adding the following(without spaces) to any page:
[ button href=”#” class=”your_class” ]Test[ /button ]

If you enjoyed this tutorial please share, helps a lot. You can also view more of our tutorials by going to our blog.

About author:

M H

I’m a freelance web designer from the UK, Scotland. Also available for freelance hire!

View all posts

Leave a Reply

Your email address will not be published. All comments are reviewed.

Fast, Secure Payments. Download Themes & Plugins instantly!

Manage your orders and downloads