WordPress and Shortcodes: In Development

The WordPress logo with a white background

This is the second part of a short series about the WordPress Shortcode API. If you would like to read the first part of the series, please read WordPress and Shortcodes: The Short Manual. In this post, we are going to create our own shortcode.

Creating a shortcode

The code needed to create a bare-bones shortcode:

function foobar_func( $atts ){
	return "foo and bar";
add_shortcode( 'foobar', 'foobar_func' );

The commented code at top is an example borrowed from the WordPress Codex page on Shortcode API. Let’s walk through the function, step-by-step.


This commented code, placed at the top of the function, will become the shortcode.

function foobar_func( $atts ){

The first thing to do is declare a function and give it a name. Then, you can insert any attributes that you would like to pass into the function.

	return "foo and bar";

Why return and not echo? Well, as in the video shown below, you should return the values, not echo them. Echoing the values will cause the shortcode to render in a strange and unpredictable way.

Finally, let’s call the function.


Let’s add the action hook to call the function:

add_shortcode('foobar', 'foobar_func');

If you would like to add attributes to your shortcode, then you will need to use the shortcode_atts function. You can find how it is used written below.

// [bartag foo="foo-value"]
function bartag_func( $atts ) {
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts );

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


If you would prefer to learn from a video, or you have been referred here, make sure to check out the video below.


In the code above, we are passing in some attributes, that will later

If you have any questions, feel free to leave a comment below. Thanks for reading!