Creating a WP shortcode for your own CSS

I have a client who would like to place some introductory text over the image she is using in the slider on her homepage. I have seen examples of giving text such as this a semi-transparent background to make it stand out clearly from the image.

st-bg_screenshot

I have created a child theme for Divi 2. Firstly I edited style.css in the child theme folder and inserted the CSS required for the background.

.st-bg {
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
    background-color: rgba(170, 170, 170, 0.50);
    margin-left: auto;
    margin-right: auto;
    padding-top: 10px;
    padding-bottom: 10px;
}
.st-bg-grey {
    background-color: rgba(170, 170, 170, 0.50);
}
.st-bg-red {
    background-color: rgba(255, 27, 17, 0.50);
}
.st-bg-green {
    background-color: rgba(0, 255, 0, 0.50);
}

This would be enough if it was only going to be used by another developer but I am intending for it to be used by non-techie customers so I would prefer it to be referenced by a shortcode. Therefore, in functions.php (again in the child theme folder) I added the code:

// Add Shortcode
function st_bg_text_shortcode( $atts , $content = null ) {

    // Attributes
    extract( shortcode_atts(
            array(
                'color' => 'grey',
            ), $atts )
    );

    $color = "st-bg-" . $color;

    // Code
    return '<div class="st-bg ' . $color . '">' . $content . '</div>';

}
add_shortcode( 'st-bg', 'st_bg_text_shortcode' );

 

Now my client can surround the text with the shortcode [st-bg color="grey"] to achieve the background shown above. As you can see I have added some styles and code for other colours.

E.g.

[st-bg color="red"]

Development Test 2

Welcome to Dev Test 2

Join Us

[/st-bg]

 

Thanks to http://generatewp.com/ for help with the coding.

Leave a Reply