How To Write WordPress Shortcode – Ins And Out

- Advertisement -
- Advertisement -

Shortcode is the great feature of WordPress. You’ll see shortcode in WordPress themes or plugins. You can make shortcode as your own way.

Open functions.php in your theme and write there below code.

function test_shortcode(){
echo "Do something!";
add_shortcode('callit', 'test_shortcode');

At first, we’ve made a function called test_shortcode() then we’ve ‘echo’ something. Last we’ve used WordPress hook add_shortcode with callit and function name. You can use any name instead of callit.

Now if you use callit as shortcode [callit] in your post or page you’ll show output Do something!

Note: it’ll create a problem when you’ll use the shortcode beneath of a text. So use return instead of echo.

Let’s try with arguments-

function test_shortcode($atts, $content){
return $content;
add_shortcode('callit', 'test_shortcode');

Now you can use it as [callit]Show something in display[/callit] and it’ll show Show something in display on the screen.

Argument example:

function user_func( $atts ) {
$a = shortcode_atts( array(
'name' = 'Default Name',
'id' = 'Default ID',
), $atts );

return 'Your name: '. $a["name"]. '. Your ID:'. $a["id"];
add_shortcode( 'user', 'user_func' );

You need to call the shortcode as [user name=”John” id=”1993″] it’ll show as Your name: John. Your ID: 1993 on the screen.

Show image with shortcode:

// Image with Shortcode
function sc_image($atts, $content){
$sc_image_show = shortcode_atts(array(
'height' => '120px',
'width' => '250px'
), $atts);
return '<img height= "'.$sc_image_show["height"].'" width= "'.$sc_image_show["width"].'" src="'.$content.'" />';
add_shortcode('image', 'sc_image');

You may use the shortcode as [image height=”50px” width=”80px”]×476.jpg[/image] you’ll see the image as your preferred size.

Use code through shortcode:

// Use code through shortcode
function sc_code_shortcode(){
ob_start(); ?>

<h1>It's heading 1</h1>
<img style="width: 80px; height: 50px" src="" alt="Malware">

<?php $sc_show_code = ob_get_clean();
return $sc_show_code;
add_shortcode('sc_show_code', 'sc_code_shortcode');

You can use a lot of code in the shortcode. Just call the shortcode like [sc_show_code] really enjoyable 🙂

You can also use the shortcode in widget. But you need to add a filter in functions.php

add_action('widget_text', 'do_shortcode');

If you like this article, then please like our Facebook Page and share it on your wall.

- Advertisement -
Web Developer & Front-end Expert



Please enter your comment!
Please enter your name here

Stay Connected

- Advertisement -