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:

//[foobar]
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.

//[foobar]

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 );


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

OUR SERVICE

Fan Commerce

ファンコマース

ファンとのダイレクトなコミュニケーションを実現して「感動体験」をビジネスに結びつけます。

Digital Marketing

デジタルマーケティング

未来を創造する価値ある「顧客体験」を実現する仕組みづくりを提案。