Multiple Parameters for a Shortcode

I am working on building some shortcodes for my blog.
I can set a single parameter for my shortcode, but not sure how to set different parameter.

For example, I can use [myshortcode myvalue] to output a html block within the post content.

Here is what I am currently using:

function test_shortcodes( $atts ) {
    extract( shortcode_atts( array(
        'myvalue' => '<div class="shortcodecontent"></div>'

    ), $atts ) );

    return $myvalue;
}
add_shortcode( 'myshortcode', 'test_shortcodes' );

Now, how can I use [myshortcode myothervalue] to output a different block of html?

Please note that the shortcode is same, only the parameter is changed.

5 Answers
5

Lets look at the shortcode

[SH_TEST var1="somevalue" var2="someothervalue"]THE SHORTCODE CONTENT[/SH_TEST]

the shortcode handler function accepts 3 paramters

  1. $atts – an array of attributes passed by the shortcode in our case:

    • $atts['var1'] is set to 'somevalue'
    • $atts['var2'] is set to 'someothervalue'
  2. $content – is a string of the value enclosed with in the shortcode tags, in our case:
    $content is set to THE SHORTCODE CONTENT

  3. $tag – is a string of the shortcode tag, in our case:
    $tag is set to SH_TEST

When I create a shortcode i usually define the default values and merge them with the values submitted by the shortcode tag ex:

add_shortcode('SH_TEST','SH_TEST_handler');
function SH_TEST_handler($atts = array(), $content = null, $tag){
    shortcode_atts(array(
        'var1' => 'default var1',
        'var2' => false
    ), $atts);

    if ($atts['var2'])
          return 'myothervalue';
    else
          return 'myvalue'; 
}

Leave a Comment