Optimize shortcode callbacks

There is a very important programming principle: DRY – Don’t repeat yourself.
Whenever you realize you are repeating almost the same job try to write an abstraction.

For your pad* shortcodes this means:

function get_padding( $atts ) 
{
    $args = shortcode_atts( 
        array( 'num' => 10 ), 
        $atts 
    );
    return str_repeat( ' ', (int) $args['num'] );
}
add_shortcode('pad', 'get_padding');

Now you can use the shortcode [pad] like this:

[pad num=5]
[pad num=10]
[pad num=12000]
[pad num=18]

The advantage is: if you decide to change the inner logic of your shortcodes you have to touch just one function, not a dozen.

See also this answer.


There is another possibility: Use one callback for multiple shortcodes. This uses the third parameter each shortcode callback gets.

function multipass( $atts, $content="", $shortcode="" )
{
    $args = shortcode_atts(
        array (
            'name' => 'example'
        ),
        $atts
    );

    $name    = esc_attr( $args['name'] );
    $content = esc_textarea( $content );

    if ( 'textarea' === $shortcode )
        return "<textarea name="$name">$content</textarea>";

    if ( 'input' === $shortcode )
        return "<input name="$name" value="$content" />";
}
add_shortcode( 'textarea', 'multipass' );
add_shortcode( 'input',    'multipass' );

Related

Leave a Comment