Web Development & WordPress

Create a Reusable WordPress Button Shortcode (Custom URL & Label Support)

If you want to add a reusable button to your WordPress posts or pages, creating a simple shortcode is the easiest way. With this shortcode, you can place a custom button anywhere on your website by passing a URL and button label as parameters.

This means you can use the same shortcode on multiple posts while changing only the link and text. For example:

[button url="https://google.com" label="Google"]
[button url="https://yahoo.com" label="Yahoo"]

Below is the code you need to add to your functions.php file. This custom shortcode will generate a styled button with hover effects, and it automatically opens the link in a new tab.

WordPress Button Shortcode Code

function customized_button( $attributes ) {

    $url = $attributes[ 'url' ];
    $label = $attributes[ 'label' ];

    // Add CSS inline with the button
    $css = "
        <style>
            .custom-button {
                display: inline-block;
                padding: 10px 20px;
                background-color: #2271b1;
                color: #ffffff;
                text-decoration: none !important;
                border-radius: 4px;
                font-weight: 500;
                transition: all 0.3s ease;
            }
            .custom-button:hover {
                background-color: #135e96;
                color: #ffffff;
                transform: translateY(-2px);
            }
        </style>
    ";
    return $css.sprintf( "<a target='_blank' class='custom-button' href='%s'>%s</a>", $url, $label );

}
add_shortcode( 'button', 'customized_button' );

Leave a comment