Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers

up vote 0 down vote accepted

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!

share|improve this answer
just like i thought. I'm going for the first option then. Thank you :) – Wordpressor Mar 3 '11 at 0:59

WordPress does not discard attributes without values as is suggested by SethMerrick, but it does not handle it as you would expect. In your example, you would not be able to check isset($atts['last']), but "last" is passed as a value to an unnamed attribute. In this case, this would result in TRUE: ($atts[0] == 'last'). So, you could do a foreach loop to check for any attribute with a value of "last".

share|improve this answer
This is how I build shortcodes for clients often. Easy to type, easy to check. – toscho Mar 23 '12 at 23:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.