Create shortcode in PHP for WordPress

Admittedly, a WordPress website without shortcuts would be almost comparable to a static HTML template. We show how you can add your own dynamic content and features to a theme or plugin.

To extend your WordPress theme or plugin with a brand new shortcode, simple steps are necessary.

Simple shortcode

The following code is placed in the functions.php file in the theme or in the plugin file

function dynamic_content_shortcode( ) {
    $content = "Inhalt";
    return $content;
add_shortcode( 'dynamic_content', 'dynamic_content_shortcode' );

With these five lines of code a new shortcode is already registered in WordPress and can be used. [dynamic_content] as shortcode would output the word “content” in this example. Here it would also be possible to add a complex function and thus generate dynamic content.

Shortcode with attributes

To give a new shortcode a little more dynamic, you can also add various attributes to the shrotcode, which were previously defined in functions.php or the plugin file.

function dynamic_content_shortcode( $atts ) {
    $atts = shortcode_atts(
            'attribute_1' => 'predefined_1'
          	'attribute_2' => 'predefined_2'
         	'attribute_3' => 'predefined_3'
        ), $atts, 'product-overview' );
  	$content = $atts['attribute_1'];
  	$content .= $atts['attribute_2'];
  	$content .= $atts['attribute_3'];
  	return $content;
add_shortcode( 'dynamic_content', 'dynamic_content_shortcode' );

$atts is predefined with an array of three elements: attribute_1, attribute_2 and attribute_3. The element names as well as the values can be freely chosen.

Example output with attribute

If the shortcode would be inserted as follows, the output would be in each case:


[dynamic_content attribute_1="manipuliert"]manipuliertpredefined_2predefined_3

[dynamic_content attribute_1="manipuliert" attribute_2="nochmals" attribute_3="und wieder"]manipuliertnochmalsund wieder

Trent Bojett

My name is Trent Bojett, I am 28 years old and I live in Switzerland. Because of my enthusiasm for writing and the logical world (= software development) I started this blog in early 2020.

Add comment


Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular

Most discussed