Mícéal Gallagher in Wordpress 2 minutes

WordPress - Create your own shortcode

A large number of WordPress plugins utilize the shortcode functionality inherent to WordPress. Shortcodes allow content creators to add significant functionality to a webpage with relative ease. I want a shortcode that will have an attribute called* name* and when this shortcode is detected it will be replaced by “Say hello name”. Open the functions.php file for your current theme and add the line below. The first parameter is the shortcode and the second is the PHP function to call when the code is encountered.

```phpadd_shortcode(‘say_hello_shortcode’, ‘sayHelloFunction’);


Now add the code for the sayHelloFunction. Notice that we have an array called *attributes;* we can reference the elements in this array with the name of an attribute whose value we desire.

```phpfunction sayHelloFunction($attributes = array()) {
    // Convert the shortcode attributes to an array
    extract(
        shortcode_atts(array(
            'title' => 'Say Hello Shortcode',
            'id' => 'say_hello_shortcode',
            'depth' => 1
	), $attributes));
    // Output the name
    $name = $attributes["name"];
    return "Say hello " . $name;
}

Now we add the following to a page using the WYSIWYG editor like so:

xhtml[say_hello_shortcode name="Miceal Gallagher"]

And now when the page renders we get this… [say_hello_shortcode name=”Miceal Gallagher”]