Shortcode empty attribute

Is there a way of creating an empty attribute for a shortcode?

Example:

function paragraph_shortcode( $atts, $content = null ) {

   return '<p class="super-p">' . do_shortcode($content) . '</p>';
}

add_shortcode('paragraph', 'paragraph_shortcode'); 

User types

[paragraph] something [/paragraph]

and it shows

<p class="super-p"> something </p>

How to add an empty attribute functionality to my first code? So when user types

[paragraph last] something
[/paragraph]

It will output:

<p class="super-p last"> something </p>

I believe adding a:

extract( shortcode_atts( array(
            'last' => '',
        ), $atts ) );

is a good start, but how to check if user used the “last” attribute while it doesn’t have a value?

6 s
6

There could be a couple ways to do this. Unfortunately, I don’t think any will result in exactly what you’re going for. ( [paragraph last] )

  1. You could just create separate shortcodes for [paragraph_first] [paragraph_last] [paragraph_foobar] that handle $content without needing any attributes

  2. You could set the default value for last to false instead of '', then require users to do [paragraph last=""]content[/paragraph]

  3. You could add a more meaningful attribute such as position which could then be used like [paragraph position="first"] or [paragraph position="last"]

Because of the fact that WordPress discards any atts not given defaults, and the fact that an att without an ="value" is given the default value same as if it’s not listed at all, I don’t see any way to achieve [paragraph last]

Hopefully one of my 3 workaround will prove useful. Good luck!

Leave a Comment