3

Some HTML elements accept valueless attributes such as <input disabled /> or <video autoplay />

How do I handle this case with shortcodes where I want to disable autoplay by default (= omit the attribute at all) but enable it optionally.

Possible scenarios:

// [video]
<video>

// [video autoplay]
<video autoplay="autoplay"> // using XML syntax

// [video autoplay="autoplay"]
<video autoplay="autoplay"> 

// [video autoplay="false"]
<video autoplay="false"> // value doesn't matter - video will still auto play

The standard way of doing this doesn't help me as I don't want to have a default value:

// http://codex.wordpress.org/Shortcode_API#Attributes
function my_shortcode_handler( $atts, $content = null ) {
    extract( shortcode_atts( array(
        'attr_1' => 'attribute 1 default',
        'attr_2' => 'attribute 2 default',
    // ...etc
    ), $atts ) );
}

I can definitely find my own hack around this problem but I am interested if there is a pretty way to do this.

2

Use 0 and 1 as shortcode values and use that show or hide the HTML attribute.

Example with an element input and the attribute required:

function input_shortcode( $atts )
{
    $values = shortcode_atts(
        array (
            'type'     => 'text',
            'value'    => '',
            'name'     => '',
            'id'       => '',
            'required' => 0,
        ),
        $atts
    );

    $values = array_map( 'esc_attr', $values );

    return sprintf(
        '<input type="%1$s"%2$s%3$s%4$s%5$s>',
        $values[ 'type' ], // 1
        '' === $values[ 'name' ]     ? '' : ' ' . $values[ 'name' ], // 2
        '' === $values[ 'value' ]    ? '' : ' ' . $values[ 'value' ], // 3
        '' === $values[ 'id' ]       ? '' : ' ' . $values[ 'id' ], // 4
        0  === $values[ 'required' ] ? '' : ' required' // 5
    );
}

Please don’t use extract(). Ever.

3
1

Nameless attributes are still getting passed to shortcode handler, they just can't be accessed by name (because, duh!)

You could loop through attributes with numeric keys and check for presence of autoplay value, thus achieving [video autoplay] variant.

See similar question - Shortcode But Without The Equals Sign?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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