Amazing WordPress shortcode tutorial

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

Amazing WordPress shortcode tutorial

This amazing WordPress shortcode is very useful, probably one of the best. It’s also good for combining a couple together however, in this tutorial we’ll just be creating a div that displays the content withing it.

1.) Let’s start by adding our function and shortcode


function mhweb_div_shortcode($atts = [], $content = null, $tag = '')
{

    //code goes here

}

function mhweb_div_shortcode_init()
{
add_shortcode('mhweb_div_shortcode', 'mhweb_div_shortcode');
}

add_action('init', 'mhweb_div_shortcode_init');

2.) Now we’ll add our attributes, you can add your own


    // normalize attributes
    $atts = array_change_key_case((array)$atts, CASE_LOWER);

    // add our attributes
    $mhweb_atts = shortcode_atts([
       'class' => '',
    ], $atts, $tag);

3.) Now our outputs this is were you create your div tag’s


    // start output
    $mhweb = '';

    // enclosing tags
    if (!is_null($content)) {
       // secure output by executing the_content filter hook on $content
       $o .= ' <div class="'. esc_html__($mhweb_atts['class'], 'mhweb') . '" > '.$content.' </div>';

    }

    // end of our div
    $mhweb .= '</div>';

    // return output
    return $mhweb;

You’re finished! Your code should look like this:


//mhweb_div_shortcode
function mhweb_div_shortcode($atts = [], $content = null, $tag = '')
{

    // normalize attributes
    $atts = array_change_key_case((array)$atts, CASE_LOWER);

    // add our attributes
    $mhweb_atts = shortcode_atts([
       'class' => '',
    ], $atts, $tag);

    // start output
    $mhweb = '';

    // enclosing tags
    if (!is_null($content)) {
       // secure output by executing the_content filter hook on $content
       $mhweb .= ' <div class="'. esc_html__($mhweb_atts['class'], 'mhweb') . '" >'.$content.' </div>';

    }

    // end of our div
    $mhweb .= '</div>';

    // return output
    return $mhweb;

}

function mhweb_div_shortcode_init()
{
add_shortcode('mhweb_div_shortcode', 'mhweb_div_shortcode');
}
add_action('init', 'mhweb_div_shortcode_init');

You can view more of our tutorials!

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