Your short code function receives the attributes as the first argument:
function shortcode_function( $attributes ) {
Here $attributes
is an array, and the attributes/values are inside that variable,
e.g. for [my-shortcode abc="123" xyz="789"]
:
echo $attributes['abc']; // prints 123
echo $attributes['xyz']; // prints 789
You should also provide defaults and an opportunity to filter:
$attributes = shortcode_atts( [
'id' => '',
], $attributes );
This way if the id
is missing you don’t get PHP warnings, e.g. if we wrote [my-shortcode]
by accident.
Improving The Shortcode
First, lets add type hints. This will avoid a common pitfall/bug that people fall into:
function shortcode_function( array $attributes ) : string {
Here we’ve told PHP that attributes is an array, and that this function returns a string, aka the content of our shortcode.
This give us:
function shortcode_function( array $attributes ) : string {
// get the attributes
$attributes = shortcode_atts( [
'id' => 'default ID value goes here',
], $attributes );
$id = $attributes['id'];
// generate the shortcode's content:
return 'My ID is:' . $id;
}
add_shortcode( 'my-shortcode', 'shortcode_function' );