Shortcodes in WordPress allow you to add dynamic content easily. They are wrapped in square brackets and processed by WordPress, enabling you to create reusable snippets. In this article, we’ll show you how to use shortcodes on your WordPress website step-by-step.
What is a Shortcode
A shortcode is a WordPress code that simplifies adding functionality. For example, “displays a gallery. Shortcodes are special tags that WordPress processes and replaces with specific content when a page or post is displayed. They were introduced in WordPress 2.5 to make it easier for users to include complex functionality without dealing with raw HTML, CSS, or PHP.
Common Uses of Shortcodes
- Embedding videos, audio, or galleries
- Displaying dynamic content like recent posts, user profiles, or testimonials
- Inserting contact forms or call-to-action buttons
- Implementing third-party services like Google Maps or social media feeds
Creating a Shortcode Function
Define the Function
Create a function that returns the desired output.
function my_custom_shortcode() { return "<p>This is my custom shortcode output!</p>"; }
Register the Shortcode
Use add_shortcode to link the shortcode to your function.
add_shortcode('my_shortcode', 'my_custom_shortcode');
Use the Shortcode
Insert the shortcode in your content:
[my_shortcode]
Shortcode Attributes
To accept attributes, modify your function with shortcode_atts.
function my_custom_shortcode($atts) { $atts = shortcode_atts( array('text' => 'Default text', 'color' => 'black'), $atts ); return "<p style='color: {$atts['color']};'>{$atts['text']}</p>"; }
Usage with Attributes
[my_shortcode text="Hello, World!" color="blue"]
Examples
Current Date
Display the current date:
function current_date_shortcode() { return date('F j, Y'); } add_shortcode('current_date', 'current_date_shortcode');
Usage:
[current_date]
Read Also:-
How to Loop Through an Array in React.JS
How To Create custom post type (CPT) in WordPress
WordPress Error Handling by Hooks
Also visit:-