DEV Community

farid teymouri
farid teymouri

Posted on • Updated on

PHP shortcode with multiple parameters

// PHP Function
function custom_greeting($atts) {
    // Extract shortcode attributes
    $atts = shortcode_atts(
        array(
            'name' => 'Guest',
            'age' => 0
        ),
        $atts
    );

    // Generate custom greeting
    $greeting = "Hello, {$atts['name']}! ";
    if ($atts['age'] > 0) {
        $greeting .= "You are {$atts['age']} years old.";
    } else {
        $greeting .= "We don't know your age.";
    }

    return $greeting;
}

// Shortcode
add_shortcode('greeting', 'custom_greeting');
Enter fullscreen mode Exit fullscreen mode

In the above code, we have a PHP function called custom_greeting that accepts an array of attributes ($atts) as a parameter. This function uses the shortcode_atts() function to merge the provided attributes with default values ('name' => 'Guest' and 'age' => 0). The function then generates a custom greeting based on the provided attributes.

To create the shortcode, we use the add_shortcode() function. The first parameter of add_shortcode() is the name of the shortcode, in this case, 'greeting'. The second parameter is the name of the PHP function to be executed when the shortcode is encountered, which is custom_greeting in this example.

Now, you can use the shortcode [greeting name="John" age="25"] in your WordPress content to display a custom greeting. The name attribute specifies the name of the person, and the age attribute specifies their age. If the age attribute is not provided, it defaults to 0.

Top comments (0)