Shortcodes let you add special content or features inside WordPress posts or pages easily. They save time by reusing code with a simple tag.
0
0
Creating shortcodes in Wordpress
Introduction
You want to add a button or special layout inside a post without writing HTML every time.
You want to insert dynamic content like the current date or user info inside pages.
You want to let non-technical users add complex features by typing a simple code.
You want to create reusable content blocks that can appear in many places.
You want to keep your content clean and separate from code.
Syntax
Wordpress
function shortcode_function_name($atts, $content = null) {
// Process attributes and content
return 'Your output here';
}
add_shortcode('shortcode_tag', 'shortcode_function_name');The function receives attributes and optional content inside the shortcode.
Use add_shortcode to register the shortcode tag and link it to your function.
Examples
This shortcode
[hello] will show "Hello, world!" wherever used.Wordpress
function hello_shortcode() {
return 'Hello, world!';
}
add_shortcode('hello', 'hello_shortcode');This shortcode
[button url="https://example.com"] creates a clickable button linking to the given URL.Wordpress
function button_shortcode($atts) {
$atts = shortcode_atts(['url' => '#'], $atts);
return '<a href="' . esc_url($atts['url']) . '" class="btn">Click me</a>';
}
add_shortcode('button', 'button_shortcode');This shortcode
[wrap]content[/wrap] wraps the content inside a div with class "wrapper".Wordpress
function wrap_shortcode($atts, $content = null) {
return '<div class="wrapper">' . do_shortcode($content) . '</div>';
}
add_shortcode('wrap', 'wrap_shortcode');Sample Program
This shortcode [greet name="Alice"] will output "Hello, Alice!". If no name is given, it says "Hello, Friend!" by default.
Wordpress
<?php // Shortcode to display a greeting with a name attribute function greet_shortcode($atts) { $atts = shortcode_atts(['name' => 'Friend'], $atts); return 'Hello, ' . esc_html($atts['name']) . '!'; } add_shortcode('greet', 'greet_shortcode'); // Usage in WordPress post: [greet name="Alice"] ?>
OutputSuccess
Important Notes
Always sanitize attributes and content to keep your site safe.
Shortcodes can be nested, but use do_shortcode() inside your function to process inner shortcodes.
Test your shortcode in posts or pages to see how it looks and works.
Summary
Shortcodes let you add reusable content with simple tags inside WordPress.
Create a function that returns the output and register it with add_shortcode.
Use attributes and content to make your shortcode flexible and dynamic.