• Email: [email protected]
  • Dedicated Server Login
  • About
  • 9288041031
  • Knowledge Base
  • Support
India's best web hosting | Ehostpiya India
  • Home
  • Hosting
    Web Hosting Quality Hosting Starting at ₹60/mo
    Cloud VPS Starting at ₹300/mo
    Dedicated Server First Starting at ₹2401/mo
    Reseller Web Hosting Conveniently Starting at ₹421/mo
    Application For Hosting
    • iconWordPress Hosting
    • iconJoomla Hosting
    • iconMagento Hosting
    • iconOpencart Hosting
    • iconPrestashop Hosting
    • iconDrupal Hosting
  • Email
  • Domain
  • SVG
    Contact Us Face any problem contact with us
    SVG
    About Us We are leading hosting company
  • My Account
Web Hosting Blogs by Ehostpiya | Tips and Tricks Web Hosting Blogs by Ehostpiya | Tips and Tricks
Buy Now

Archives

  • October 2026
  • September 2026
  • August 2026
  • October 2023

Categories

  • Control Panels
  • Magento
  • Miscellaneous
  • SEO
  • Technology
  • Trends
  • Web Hosting
  • Wordpress
Facebook Twitter Instagram Pinterest
Home How to Create a WordPress Shortcode?
ByVandeeta
October 1, 2026

How to Create a WordPress Shortcode?

Table of Contents

Toggle
  • How to Create a WordPress Shortcode
    • What Is a WordPress Shortcode?
    • Why Use Shortcodes?
    • Before Creating a Shortcode
  • Method 1: Create a Simple WordPress Shortcode
  • Understanding add_shortcode()
      • Shortcode Name
      • Callback Function
  • Important: Return Instead of Echo
  • Create a Shortcode That Outputs HTML
  • Creating a Shortcode for a Button
  • How to Add Attributes to a Shortcode
  • What Is shortcode_atts()?
  • Always Escape Shortcode Output
  • Creating a Shortcode With Content
  • Using Shortcode Attributes With Content
  • Using Shortcodes Inside Other Shortcodes
  • Creating a Shortcode That Displays the Current Year
  • Creating a Shortcode With a Custom CSS Class
  • Where Should You Add Custom Shortcode Code?
    • 1. Custom Plugin
    • 2. Child Theme functions.php
    • 3. Code Snippets Plugin
  • How to Use a Shortcode in WordPress
  • Can Shortcodes Be Used in Widgets?
  • Can Shortcodes Be Used in PHP Templates?
  • Adding a Shortcode to a Custom Plugin
  • Common Shortcode Mistakes
    • 1. Using echo Instead of return
    • 2. Using a Generic Shortcode Name
    • 3. Forgetting to Escape Output
    • 4. Adding Too Much Functionality to One Shortcode
    • 5. Editing the Parent Theme
  • Shortcode Security Best Practices
      • Validate input
      • Escape output
      • Use nonces when handling actions
      • Check user capabilities
      • Avoid executing arbitrary PHP
  • Shortcode vs Custom Block
  • Shortcode vs Plugin
  • Example: Complete Custom Shortcode
  • Best Practices for WordPress Shortcodes
  • Troubleshooting WordPress Shortcodes
    • Shortcode Appears as Plain Text
    • Shortcode Produces a Blank Area
    • Shortcode Causes a PHP Error
    • Shortcode Conflicts With Another Plugin
  • Frequently Asked Questions
    • What is a WordPress shortcode?
    • Where should I add shortcode PHP code?
    • Can a shortcode accept parameters?
    • Can a shortcode contain content?
    • Should a shortcode echo or return content?
    • Can shortcodes be used in PHP templates?
    • Are shortcodes still useful in WordPress?
  • Final Thoughts

How to Create a WordPress Shortcode

WordPress shortcodes provide a simple way to insert dynamic content into posts, pages, widgets, and other areas of a website without repeatedly writing complex HTML or PHP code.

A shortcode looks like a small piece of text enclosed in square brackets, such as:

[my_shortcode]

When WordPress processes the page, it detects the shortcode and replaces it with the content generated by the associated PHP function.

In this guide, you’ll learn how to create a custom WordPress shortcode, pass attributes to it, accept content between shortcode tags, and follow security and performance best practices.


What Is a WordPress Shortcode?

A WordPress shortcode is a special tag that allows users to execute predefined functionality inside WordPress content.

For example:

[contact_box]

could display:

Need help? Contact our support team today.

Instead of manually entering the same HTML every time, you can simply insert the shortcode wherever you want the content to appear.

WordPress includes several built-in shortcodes, while developers can create their own using PHP.


Why Use Shortcodes?

Shortcodes are useful when you want to reuse specific functionality throughout a website.

Common applications include:

  • Call-to-action boxes
  • Buttons
  • Contact information
  • Product displays
  • Pricing tables
  • Custom notices
  • Download links
  • Dynamic content
  • Custom forms
  • Frequently used HTML layouts
  • Information pulled from WordPress data

For example, instead of repeatedly adding a complex button structure, you could use:

[hosting_button]

This makes content easier to manage and reuse.


Before Creating a Shortcode

Before adding custom PHP code to WordPress, create a backup of your website.

It is also preferable to test custom code on a staging website before applying it to a production site.

There are several places where you can add shortcode code:

  1. A custom plugin
  2. A child theme’s functions.php
  3. A code snippets plugin

For functionality that should remain available even when the theme changes, a custom plugin is generally the better choice.


Method 1: Create a Simple WordPress Shortcode

Let’s create a basic shortcode called:

[welcome_message]

Add the following PHP code to a custom plugin or your child theme’s functions.php file:

function ehostpiya_welcome_message() {
    return 'Welcome to our website!';
}

add_shortcode('welcome_message', 'ehostpiya_welcome_message');

You can now add this shortcode to a WordPress post or page:

[welcome_message]

WordPress will execute the function and display:

Welcome to our website!

Understanding add_shortcode()

The following line registers the shortcode:

add_shortcode('welcome_message', 'ehostpiya_welcome_message');

It contains two important parameters:

add_shortcode('shortcode_name', 'callback_function');

Shortcode Name

This is the name users enter inside square brackets:

[welcome_message]

Callback Function

This is the PHP function WordPress calls when it finds the shortcode:

ehostpiya_welcome_message

Important: Return Instead of Echo

One of the most important rules when creating WordPress shortcodes is to return the output rather than echo it.

Correct:

function ehostpiya_message() {
    return 'Hello from WordPress!';
}

Avoid:

function ehostpiya_message() {
    echo 'Hello from WordPress!';
}

Shortcode callbacks are expected to return their generated content.

Returning the output allows WordPress to place the shortcode result correctly within the page content.


Create a Shortcode That Outputs HTML

Shortcodes become more useful when they generate HTML.

For example:

function ehostpiya_notice() {
    return '<div class="custom-notice">This is a custom WordPress notice.</div>';
}

add_shortcode('notice', 'ehostpiya_notice');

Use it inside your content:

[notice]

The shortcode will generate:

<div class="custom-notice">This is a custom WordPress notice.</div>

You can then style the .custom-notice class with CSS.


Creating a Shortcode for a Button

A common shortcode application is creating reusable buttons.

Example:

function ehostpiya_button() {
    return '<a href="https://example.com" class="custom-button">Learn More</a>';
}

add_shortcode('learn_more', 'ehostpiya_button');

Use:

[learn_more]

The generated HTML will be:

<a href="https://example.com" class="custom-button">Learn More</a>

You could then add CSS:

.custom-button {
    display: inline-block;
    padding: 10px 20px;
    text-decoration: none;
    border-radius: 5px;
}

How to Add Attributes to a Shortcode

Shortcodes can accept attributes, allowing users to customize the output.

For example:

[button text="Learn More" url="https://example.com"]

Create the shortcode with:

function ehostpiya_button_shortcode($atts) {

    $atts = shortcode_atts(
        array(
            'text' => 'Click Here',
            'url'  => '#',
        ),
        $atts,
        'button'
    );

    return '<a href="' . esc_url($atts['url']) . '" class="custom-button">' .
        esc_html($atts['text']) .
        '</a>';
}

add_shortcode('button', 'ehostpiya_button_shortcode');

Now you can customize the button without changing the PHP code.

For example:

[button text="Get Started" url="https://example.com"]

Or:

[button text="View Plans" url="https://example.com/pricing"]

What Is shortcode_atts()?

The shortcode_atts() function provides default values for shortcode attributes.

For example:

$atts = shortcode_atts(
    array(
        'text' => 'Click Here',
        'url'  => '#',
    ),
    $atts,
    'button'
);

If a user writes:

[button]

WordPress will use:

text = Click Here
url = #

If the user provides attributes, those values override the defaults.


Always Escape Shortcode Output

When shortcode attributes are used to generate HTML, user-supplied values should be properly escaped.

For URLs, use:

esc_url()

For plain text, use:

esc_html()

For HTML attributes, use:

esc_attr()

For example:

return '<a href="' . esc_url($atts['url']) . '">' .
    esc_html($atts['text']) .
    '</a>';

Escaping helps prevent malicious or malformed input from being inserted into your website’s output.


Creating a Shortcode With Content

Shortcodes can also contain content between an opening and closing tag.

For example:

[box]
This is the content inside the box.
[/box]

Create the shortcode like this:

function ehostpiya_box_shortcode($atts, $content = null) {

    return '<div class="custom-box">' .
        do_shortcode($content) .
        '</div>';
}

add_shortcode('box', 'ehostpiya_box_shortcode');

The $content parameter contains everything between the opening and closing shortcode tags.


Using Shortcode Attributes With Content

You can combine attributes and enclosed content.

Example:

[box title="Important Notice"]
Remember to back up your WordPress website regularly.
[/box]

PHP:

function ehostpiya_box_shortcode($atts, $content = null) {

    $atts = shortcode_atts(
        array(
            'title' => 'Notice',
        ),
        $atts,
        'box'
    );

    return '<div class="custom-box">
        <h3>' . esc_html($atts['title']) . '</h3>
        <div>' . do_shortcode($content) . '</div>
    </div>';
}

add_shortcode('box', 'ehostpiya_box_shortcode');

This provides a flexible reusable content box.


Using Shortcodes Inside Other Shortcodes

If your shortcode contains another shortcode, you can use:

do_shortcode($content);

For example:

function ehostpiya_wrapper($atts, $content = null) {
    return '<div class="wrapper">' . do_shortcode($content) . '</div>';
}

Then:

[wrapper]
[button text="Get Started" url="https://example.com"]
[/wrapper]

WordPress processes the nested shortcode inside the wrapper.


Creating a Shortcode That Displays the Current Year

A useful example is a dynamic copyright year.

function ehostpiya_current_year() {
    return date('Y');
}

add_shortcode('current_year', 'ehostpiya_current_year');

You can then use:

© [current_year] Your Company

The shortcode automatically displays the current year.

A WordPress-specific alternative is:

function ehostpiya_current_year() {
    return wp_date('Y');
}

add_shortcode('current_year', 'ehostpiya_current_year');

Using WordPress’s date functions is preferable because they respect the site’s configured timezone.


Creating a Shortcode With a Custom CSS Class

You can generate markup with a dedicated class:

function ehostpiya_info_shortcode($atts, $content = null) {

    return '<div class="ehostpiya-info">' .
        do_shortcode($content) .
        '</div>';
}

add_shortcode('info', 'ehostpiya_info_shortcode');

Then add CSS:

.ehostpiya-info {
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 8px;
    margin: 20px 0;
}

Use:

[info]
Your information goes here.
[/info]

Where Should You Add Custom Shortcode Code?

There are several options.

1. Custom Plugin

A custom plugin is often the best solution for site functionality.

For example:

wp-content/
└── plugins/
    └── custom-shortcodes/
        └── custom-shortcodes.php

The plugin file could contain:

<?php
/**
 * Plugin Name: Custom Shortcodes
 * Description: Adds custom shortcodes to WordPress.
 * Version: 1.0.0
 */

function ehostpiya_message_shortcode() {
    return 'Welcome to our website!';
}

add_shortcode('welcome_message', 'ehostpiya_message_shortcode');

Activate the plugin from the WordPress admin dashboard.

The shortcode will then be available throughout the website.


2. Child Theme functions.php

You can also add the shortcode to:

/wp-content/themes/your-child-theme/functions.php

This approach can work well for functionality specifically tied to the child theme.

However, if you change themes, the shortcode functionality will no longer be loaded.


3. Code Snippets Plugin

Another convenient option is using a reputable code snippets plugin.

This allows you to add PHP without directly editing theme files.

It can be especially useful when you do not want to manually modify functions.php.


How to Use a Shortcode in WordPress

After registering the shortcode, you can insert it into compatible WordPress content areas.

For example:

[welcome_message]

Depending on the WordPress editor and the location, you can use a Shortcode block in the block editor.

You can also use shortcodes in classic editor content.

Some themes and plugins provide additional shortcode-compatible areas.


Can Shortcodes Be Used in Widgets?

Shortcode support depends on the widget or block being used.

In WordPress environments where shortcode processing is supported, you can place something such as:

[welcome_message]

inside the appropriate content area.

If a shortcode appears as plain text instead of being processed, check whether that particular widget, block, theme, or plugin applies shortcode processing.


Can Shortcodes Be Used in PHP Templates?

Yes.

If you need to execute a shortcode directly from a PHP template, use:

echo do_shortcode('[welcome_message]');

For a shortcode with attributes:

echo do_shortcode('[button text="Learn More" url="https://example.com"]');

Use this approach carefully, especially when the shortcode contains user-controlled values.


Adding a Shortcode to a Custom Plugin

For larger websites, it is useful to keep custom shortcodes organized inside a plugin.

For example:

custom-shortcodes/
├── custom-shortcodes.php
├── includes/
│   └── shortcodes.php
├── assets/
│   ├── css/
│   │   └── shortcodes.css
│   └── js/
│       └── shortcodes.js

The main plugin file can load the shortcode functionality.

This structure becomes easier to maintain as the number of shortcodes increases.


Common Shortcode Mistakes

1. Using echo Instead of return

Incorrect:

function my_shortcode() {
    echo 'Hello';
}

Correct:

function my_shortcode() {
    return 'Hello';
}

2. Using a Generic Shortcode Name

Avoid extremely generic names such as:

[button]

if another plugin may already register the same shortcode.

A more unique naming convention can reduce conflicts:

[ehostpiya_button]

Prefixing functions and shortcode names is a useful practice for custom development.


3. Forgetting to Escape Output

Avoid directly inserting untrusted values into HTML.

Instead of:

return '<a href="' . $atts['url'] . '">' . $atts['text'] . '</a>';

use:

return '<a href="' . esc_url($atts['url']) . '">' .
    esc_html($atts['text']) .
    '</a>';

4. Adding Too Much Functionality to One Shortcode

A shortcode should ideally perform one clear task.

Instead of creating one shortcode responsible for an entire complex application, consider separating functionality into appropriate functions, classes, plugins, or blocks.


5. Editing the Parent Theme

Avoid putting custom shortcode functionality directly into a parent theme’s functions.php.

Theme updates can overwrite your modifications.

A child theme or custom plugin is safer.


Shortcode Security Best Practices

When developing custom shortcodes:

Validate input

Make sure shortcode attributes contain appropriate values.

Escape output

Use the appropriate WordPress escaping function before displaying dynamic data.

Use nonces when handling actions

If a shortcode creates forms or performs administrative actions, implement WordPress nonce protection where appropriate.

Check user capabilities

If the shortcode exposes privileged functionality, verify the current user’s permissions.

Avoid executing arbitrary PHP

Never design a shortcode that accepts PHP code from normal website content and executes it.


Shortcode vs Custom Block

Shortcodes remain useful, but modern WordPress development increasingly uses blocks.

A shortcode may be appropriate when:

  • You need a simple reusable content element.
  • You are maintaining an existing shortcode-based website.
  • You need a quick dynamic output mechanism.
  • The content is primarily text-based.

A custom block may be preferable when:

  • Users need a visual editing interface.
  • The component has many configurable options.
  • You want a richer editing experience.
  • You are developing a modern block-based WordPress site.

Shortcode vs Plugin

A shortcode is a piece of functionality.

A plugin is a package that can contain one or many features, including shortcodes.

For example:

Plugin
 ├── Shortcode
 ├── Settings
 ├── Admin interface
 ├── CSS
 └── JavaScript

Therefore, a custom plugin can be an excellent place to store important shortcode functionality.


Example: Complete Custom Shortcode

Here is a practical shortcode that creates a reusable hosting promotion box:

function ehostpiya_hosting_box($atts) {

    $atts = shortcode_atts(
        array(
            'title' => 'Web Hosting',
            'text'  => 'Fast and reliable hosting for your website.',
            'url'   => '#',
        ),
        $atts,
        'hosting_box'
    );

    return '<div class="hosting-box">
        <h3>' . esc_html($atts['title']) . '</h3>
        <p>' . esc_html($atts['text']) . '</p>
        <a href="' . esc_url($atts['url']) . '" class="hosting-button">
            Get Started
        </a>
    </div>';
}

add_shortcode('hosting_box', 'ehostpiya_hosting_box');

You can use:

[hosting_box
title="Premium Web Hosting"
text="Launch your website with fast and reliable hosting."
url="https://example.com"]

This approach lets you reuse the same component with different content.


Best Practices for WordPress Shortcodes

Follow these practices when creating custom shortcodes:

  1. Use unique shortcode names.
  2. Prefix custom PHP functions to prevent naming conflicts.
  3. Return shortcode output instead of echoing it.
  4. Use shortcode_atts() for default attributes.
  5. Escape dynamic output.
  6. Keep shortcodes focused on one purpose.
  7. Store important functionality in a custom plugin.
  8. Test shortcodes on desktop and mobile layouts.
  9. Check compatibility with your theme and plugins.
  10. Avoid unnecessary database queries.
  11. Keep generated HTML semantic and accessible.
  12. Document custom shortcode attributes.
  13. Test empty or invalid attribute values.
  14. Use proper permission and security checks when needed.

Troubleshooting WordPress Shortcodes

Shortcode Appears as Plain Text

If you see:

[my_shortcode]

instead of the expected output, check:

  • Whether the shortcode was registered.
  • Whether the PHP code contains a syntax error.
  • Whether the plugin is activated.
  • Whether the shortcode name is correct.
  • Whether the location supports shortcode processing.

Shortcode Produces a Blank Area

Check the callback function.

Make sure it returns something:

return 'Content';

rather than only executing an action or producing no output.


Shortcode Causes a PHP Error

Review the PHP syntax and WordPress debug log.

For temporary development debugging, you can enable WordPress debugging in wp-config.php:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Avoid displaying PHP errors publicly on a production website.


Shortcode Conflicts With Another Plugin

Two plugins can potentially register the same shortcode name.

Use a unique naming convention, such as:

[ehostpiya_button]

[ehostpiya_notice]

[ehostpiya_hosting_box]

This reduces the possibility of conflicts.


Frequently Asked Questions

What is a WordPress shortcode?

A shortcode is a special tag such as [example] that WordPress replaces with dynamically generated content.

Where should I add shortcode PHP code?

For site functionality, a custom plugin is generally a good choice. A child theme’s functions.php can also be used when the functionality is specifically associated with that theme.

Can a shortcode accept parameters?

Yes. Shortcodes can accept attributes such as:

[button text="Buy Now" url="https://example.com"]

Can a shortcode contain content?

Yes. You can create enclosed shortcodes:

[box]
Your content here
[/box]

Should a shortcode echo or return content?

A shortcode callback should return its generated content.

Can shortcodes be used in PHP templates?

Yes. You can process one using:

echo do_shortcode('[my_shortcode]');

Are shortcodes still useful in WordPress?

Yes. They remain useful for simple reusable dynamic content and for compatibility with existing WordPress sites, although custom blocks are often a better choice for complex visual editing experiences.


Final Thoughts

Creating a WordPress shortcode is a straightforward way to turn reusable PHP functionality into a simple content tag.

A basic shortcode requires only two main components: a PHP callback function and add_shortcode(). From there, you can add attributes, enclosed content, dynamic data, HTML output, and styling to create more powerful components.

For small projects, a shortcode can be added through a child theme or code snippets solution. For functionality that should survive theme changes, a custom plugin is usually a more maintainable approach.

As your WordPress development skills grow, shortcodes can also serve as a useful stepping stone toward more advanced solutions such as custom plugins, REST API integrations, and custom Gutenberg blocks.

ByVandeeta
Updated October 01, 2026
  • Wordpress

Read Next

ByVandeeta
October 1, 2026

How to Use the WordPress REST API?

How to Use the WordPress REST API The WordPress REST API allows applications and services to communicate with…
  • Wordpress
ByVandeeta
October 1, 2026

How to Create a WordPress Staging Website?

Here’s a unique, SEO-friendly tutorial suitable for a WordPress/web-hosting knowledge base. How to Create a WordPress Staging Website…
  • Wordpress
ByVandeeta
October 1, 2026

How to Clone a WordPress Website

How to Clone a WordPress Website Cloning a WordPress website means creating a complete copy of an existing…
  • Wordpress

Leave a Reply Cancel reply

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

Explore Categories

  • Control Panels 7
  • Magento 52
  • Miscellaneous 5
  • SEO 17
  • Technology 10
  • Trends 9
  • Web Hosting 7
  • Wordpress 100

Recent Posts

  • How to Fix WordPress “Too Many Redirects”
  • How to Fix WordPress Critical Error
  • How to Fix WordPress Database Connection Error
  • How to Fix WordPress White Screen of Death
  • How to Fix WordPress 404 Error

Recent Comments

  1. Tabias H. on The Future is 5G: Understanding the Next Wave of Connectivity
  2. Elliot Alderson on Evolving Workspaces: The Rise of the Hybrid Work Trend
  3. James Mann on Evolving Workspaces: The Rise of the Hybrid Work Trend
Swyft

Welcome to the Ehostpiya Blog, your trusted resource for web hosting, WordPress, VPS, domains, website security, and online business tips.

Our goal is to make web hosting and website management easier to understand for everyone—from beginners launching their first website to experienced developers and business owners. We publish practical guides, hosting tips, tutorials, and helpful insights to help you build, manage, and grow your website successfully.

At Ehostpiya, we believe that reliable information and quality hosting go hand in hand. Explore our latest articles and discover simple solutions for a faster, safer, and more successful online presence.

  • Facebook
  • Twitter
  • Instagram
  • Pinteres

Featured Posts

  • AI and Ethics: Navigating the Complex Landscape of Artificial Intelligence
    by Vandeeta
    October 11, 2023
  • AR and VR: Blurring the Lines Between Reality and Virtuality
    by Vandeeta
    October 11, 2023
  • Best WordPress Caching Plugins to Improve Website Speed
    by Vandeeta
    September 26, 2026
  • Blockchain Unchained: How Distributed Ledger Technology is Transforming Industries
    by Vandeeta
    October 11, 2023

Web Hosting Discount

cLAIM NOW
logo

Ehostpiya is reliable Web hosting provider, with aim to provide affordable Website and application hosting to various clients for their online business and presence.

Hosting
  • Web Hosting
  • Cloud VPS
  • Reseller Hosting
  • Email Hosting
  • Dedicated Server
  • Nodejs Hosting
  • SSL Certificate
Legal
  • Accepted Uses Policy
  • privacy Policy
  • Terms of Service
  • Refund and cancellation
  • Service Delivery Policy
Company
  • About Us
  • Our Clients
  • Contact Us
  • Our Blog
Support & Tools
  • Open Support Request
  • View Ticket
  • Knowledge Base
  • Report Abuse
  • check nameserver
  • What is my IP
  • Mx lookup

© Ehostpiya, All rights reserved

  • Terms & Condition
  • Privacy Policy