How to have the same shortcode multiple times on a page with different attribute values

Viewed 458

So I basically need to have the same shortcode multiple times on the same page with different attribute values.

So on my page, I have the following shortcode:

[sponsors type="Platinum"]
[sponsors type="Premium"]
[sponsors type="Plus"]

Then I have multiple if statements which all state the following:

if ( $atts['type'] == 'Platinum' ) {
?>
<h2><?php echo 'working'?></h2>
<?php
} else {}

if ( $atts['type'] == 'Premium' ) {
?>
<h2><?php echo 'working'?></h2>
<?php
} else {}

if ( $atts['type'] == 'Plus' ) {
?>
<h2><?php echo 'working'?></h2>
<?php
} else {}

But I noticed when I do this the values just combine and are not specific to each shortcode as when I dumped $atts['type'] I got this string 'Platinum Premium Plus'.

So not sure how else I can do this?

1 Answers

How to have the same shortcode multiple times on a page with different attribute values

Exactly how you've done it:

[sponsors type="Platinum"]
[sponsors type="Premium"]
[sponsors type="Plus"]

The thing is that shortcodes don't echo stuff, they have to return a string with your code.

Like so:

add_shortcode('sponsors', function($atts,$content){
    if ( $atts['type'] == 'Platinium' ) {
        $result = "<h2>Platinum working</h2>";
    }
    else if ( $atts['type'] == 'Premium' ) {
        $result = "<h2>Premium working</h2>";
    }
    else if ( $atts['type'] == 'Plus' ) {
        $result = "<h2>Plus working</h2>";
    }
    return $result;
});
Related