How to create shortcodes with options in WordPress

I’m struggling a bit to get my head around how to create shortcodes with options for a theme i’m building.

The shortcode creates a container and I want a “style” parameter so the user could enter something like this:

Read More
[container style="white"]content[/container]

I have three styles: white, clear and color and each style should add the class style1, style2 and style 3 respectively to the container html. This is what I have so far in my php:

// Container

function container($atts, $content = null) {
   extract( shortcode_atts( array(
      'style' => 'style2',
     ), $atts ) );
    $return_string = '<section class="wrapper special container {$style}">'. do_shortcode($content) .'</section>';

    wp_reset_query();
   return $return_string;
}

I just wanted to make a start by getting it to register 1 style but I can’t even get to that point yet, let alone the three different styles!

Currently this just outputs:

<section class="wrapper special container {$style}">[MY CONTENT]</section>

in the html – any help or advise would be great.

Related posts

Leave a Reply

1 comment

  1. 1] Try using a switch on the $style variable to echo out the corresponding $return_string depending on it’s value.

    2] Pay special attention to the default: case, as it is what will be displayed if $style is not set to clear or white. I set it to have no attribute, but you might want it to be different.

    3] You can add as many cases as you need for the shortcode. Whatever the value of $style is will determine which $return_string is used.

    function container($atts, $content = null) {
       extract( shortcode_atts( array(
          'style' => '',
         ), $atts ) );
    
        switch ($style) {
    
            case "clear":
            $return_string = "<section class="wrapper special container style1">". do_shortcode($content) ."</section>"; // Adds style1 if clear
            break;
    
            case "white":
            $return_string = "<section class="wrapper special container style2">". do_shortcode($content) ."</section>"; // Adds style2 if white
            break;
    
            default:
            $return_string = "<section class="wrapper special container">". do_shortcode($content) ."</section>"; // No Attribute (default)
            break;
    
            }
       wp_reset_query();
       return $return_string;
    }