Complete the code to register a shortcode named 'hello'.
<?php
function hello_shortcode() {
return 'Hello, world!';
}
add_shortcode('[1]', 'hello_shortcode');The add_shortcode function registers a shortcode with the given name. Here, the shortcode name is 'hello'.
Complete the code to return a dynamic message with the user's name passed as an attribute.
<?php
function greet_user_shortcode($atts) {
$atts = shortcode_atts(['name' => 'Guest'], $atts);
return 'Hello, ' . [1] . '!';
}
add_shortcode('greet_user', 'greet_user_shortcode');The attribute array $atts contains the shortcode attributes. We use $atts['name'] to get the user's name or default to 'Guest'.
Fix the error in the shortcode function to properly handle attributes and return a message.
<?php function welcome_shortcode([1]) { $atts = shortcode_atts(['user' => 'Visitor'], $atts); return 'Welcome, ' . $atts['user'] . '!'; } add_shortcode('welcome', 'welcome_shortcode');
$atts inside.The function parameter must be named $atts to match the variable used inside the function for attributes.
Fill both blanks to create a shortcode that outputs the current year dynamically.
<?php
function current_year_shortcode() {
return date([1]);
}
add_shortcode([2], 'current_year_shortcode');The PHP date function uses 'Y' to get the full year. The shortcode name is 'current_year' to be used in posts.
Fill all three blanks to create a shortcode that accepts a 'color' attribute and returns a colored text span.
<?php function colored_text_shortcode([1]) { $atts = shortcode_atts(['color' => 'black', [2]], $atts); return '<span style="color: ' . $atts['color'] . ';">' . [3] . '</span>'; } add_shortcode('colored_text', 'colored_text_shortcode');
The function receives $atts. The default attribute 'text' is set to 'Sample Text'. The returned span uses $atts['text'] to show the colored text.