Add/Create Shortcode with Arguments


Shortcodes are pretty useful in wordpress to show static/dynamic custom content according to your needs. You can use shortcodes to show dynamic content like Posts, Categories, Products, etc. Many WordPress plugins and themes use shortcodes to add specialized content like contact forms, image galleries, sliders, and many more. If you’re thinking to learn WordPress backend, shortcodes would be a good start.

Simple Shortcode

Create a Shortcode

Paste this code inside theme’s functions.php file.

<?php
function function_name() {
    echo “This is my first Shortcode!”;
}
add_shortcode(“shortcode_name”,”function_name”);
?>

Add Shortcode

Use shortcode in Text Editor

[shortcode_name]

Use shortcode using PHP

<?= do_shortcode(“[shortcode_name]”) ?>

Output

This is my first Shortcode!

Shortcode with Arguments

Create Shortcode with Arguments

Paste this code inside theme’s functions.php file.

<?php
function function_name($args) {
    $name = $args[“name”];
    echo “My name is {$name}.”;
}
add_shortcode(“shortcode_name”,”function_name”);
?>

Add Shortcode with Arguments

Use Text Editor to print Shortcode

[shortcode_name name=‘Sanchit’]

Use below code to print shortcode using php.

<?= do_shortcode(“[shortcode_name name=‘Sanchit’]”) ?>

Output

My name is Sanchit.

Leave a Reply

Your email address will not be published. Required fields are marked *