how to create custom wordpress shortcodes

wordpress shortcodes are used in custom themes and plugins. so here in this wordpress tutorial, we will show, how to create custom shortcodes in wordpress theme.

how to create custom wordpress shortcodes

We want use wordpress shortcode in text widget and we can use shortcodes in wordpress posts. Here we will show how easily you can create wordpress shortcodes and use it.

Here using following code you can create simple shortcode. You just need to copy and paste following code in functions.php file (theme folder). If you cant to use shortcode for plugin then add this code in plugin file.

//[simple_shortcode]
function simple_shortcode_function( $atts ){
    return "foo and bar";
}
add_shortcode( 'simple_shortcode', 'simple_shortcode_function' );

Using attributes you can create short code as follows:

// [attribute_sample attr1="attr1-value"]
function attribute_sample_function( $atts ) {
    $a = shortcode_atts( array(
        'attr1' => 'something text',
        'attr2' => 'something text else',
    ), $atts );

    return "foo = {$a['foo']}";
}
add_shortcode( 'attribute_sample', 'attribute_sample_function' );

Three parameters are passed to the shortcode callback function. You can choose to use any number of them including none of them.

  • $atts – an associative array of attributes, or an empty string if no attributes are given
  • $content – the enclosed content (if the shortcode is used in its enclosing form)
  • $tag – the shortcode tag, useful for shared callback functions

Here is detailed example.

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

$our_attr =  shortcode_atts( array(
        'subtype' => 'RSS',
        'subtypeurl' => 'http://feeds.feedburner.com/wordpressapi',
    ), $atts ) ;

    return sprtinf( ' . $content . ' <a href="%1$s">by %2$s</a>.',
        esc_url( $our_attr['subtype'] ),
        esc_html( $our_attr['subtypeurl'] )
    );
 
    return '<span class="caption">' . $content . '</span>';
}
add_shortcode( 'rssfeed_subscribe', 'subscribe_shortcode' );

 

Above we created simple feedburner subscription short code. You can use above short code as follows:
[rssfeed_subscribe subtype=”RSS”]
Be sure to subscribe to future WordPress API updates
[/rssfeed_subscribe]

how to create custom wordpress shortcodes
how to create custom wordpress shortcodes