Shortcode functions 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.
What is a Shortcode
Shortcode functions in WordPress are the code that simplifies adding functionality. For example, [‘my_shortcode’]
displays the paragraph.
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>";
}
function my_custom_shortcode() {
return "<p>This is my custom shortcode output!</p>";
}
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');
add_shortcode('my_shortcode', 'my_custom_shortcode');
add_shortcode('my_shortcode', 'my_custom_shortcode');
Use the Shortcode
Insert the shortcode in your content:
[my_shortcode]
[my_shortcode]
[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>";
}
function my_custom_shortcode($atts) {
$atts = shortcode_atts(
array('text' => 'Default text', 'color' => 'black'),
$atts
);
return "<p style='color: {$atts['color']};'>{$atts['text']}</p>";
}
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"]
[my_shortcode text="Hello, World!" color="blue"]
[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');
function current_date_shortcode() {
return date('F j, Y');
}
add_shortcode('current_date', 'current_date_shortcode');
function current_date_shortcode() { return date('F j, Y'); } add_shortcode('current_date', 'current_date_shortcode');
Usage:
[current_date]
[current_date]
[current_date]
Read Also:-
Using Shortcode Functions in WordPress
How to Add Google Fonts to Your WordPress Site
Also Visit:- https://inimisttech.com/