<?php
function greet_shortcode() {
return 'Hello, friend!';
}
add_shortcode('greet', 'greet_shortcode');
?>The shortcode function returns the string 'Hello, friend!'. WordPress replaces the shortcode with this returned string in the page content.
<?php
function colorbox_shortcode($atts) {
$atts = shortcode_atts(array(
'color' => 'blue'
), $atts);
return '<div style="background-color:' . esc_attr($atts['color']) . '; width:100px; height:100px;"></div>';
}
add_shortcode('colorbox', 'colorbox_shortcode');
?>This code uses shortcode_atts to set a default color and safely outputs the div with the color style. Returning the string is correct for shortcodes.
<?php
function show_date_shortcode() {
echo date('Y-m-d');
}
add_shortcode('showdate', 'show_date_shortcode');
?>Shortcodes require the function to return the content string. Echoing outputs content immediately and returns nothing, so the shortcode outputs empty.
<?php
function inner_shortcode() {
return 'Inner';
}
function outer_shortcode() {
return 'Outer ' . do_shortcode('[inner]');
}
add_shortcode('inner', 'inner_shortcode');
add_shortcode('outer', 'outer_shortcode');
?>The outer shortcode returns 'Outer ' plus the result of processing the inner shortcode, which returns 'Inner'. So the final output is 'Outer Inner'.
<?php
function array_shortcode() {
return ['Hello', 'World'];
}
add_shortcode('arraytest', 'array_shortcode');
?>Returning an array causes PHP to warn about converting array to string and outputs the word 'Array' in place of the shortcode.
