WordPress: Create Shortcodes
WordPress shortcodes can run predefined functions from within a page or post. Adding your own custom shortcode can provide more functionality to a website.
Shortcodes can pass information into your function using its own set of attributes. For our example we will be looking at a shortcode that takes a website name and URL and displays a paragraph in the page.
To add a shortcode to your site add the following to your plugins php code or your themes functions.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/*Front Page Shortcode*/ /*[exampleplugin_shortcode sitename="Example Site Name" siteurl="https://example.com/"]*/ function exampleplugin_shortcode( $atts ){ /*Set allowable attributes*/ $a = shortcode_atts( array( 'sitename' => 'Example Site Name', 'siteurl' => 'https://example.com/', ), $atts ); /*Set attributes*/ $exampleplugin_sitename = "{$a['sitename']}"; $exampleplugin_siteurl = "{$a['siteurl']}"; /*Set the output code*/ $exampleplugin_shortcode_output = ""; $exampleplugin_shortcode_output .= '<p>Access the site with the following link: <a href="'.$exampleplugin_siteurl.'" target="_new">'.$exampleplugin_sitename.'</a></p>'; /*Return the output code*/ return $exampleplugin_shortcode_output; } /*Register the shortcode*/ add_shortcode( 'exampleplugin', 'exampleplugin_shortcode' ); |
When defining a shortcode I like to provide the shortcode usage in the comment header. In the example above we have stated the shotcode is called with the name exampleplugin_shortcode and can support the sitename and siteurl attributes.
1 |
/*[exampleplugin_shortcode sitename="Example Site Name" siteurl="https://example.com/"]*/ |
Now we start the function we want to tie with the shortcode then set the attribute and their defaults in case the user doesn’t provide any.
1 2 3 4 5 6 |
function exampleplugin_shortcode( $atts ){ /*Set allowable attributes*/ $a = shortcode_atts( array( 'sitename' => 'Example Site Name', 'siteurl' => 'https://example.com/', ), $atts ); |
We then set the attributes to variables (optional) and run whatever code we want and store what we want to return to the page in an output variable and return it when were done.
1 2 3 4 5 6 7 8 |
/*Set attributes*/ $exampleplugin_sitename = "{$a['sitename']}"; $exampleplugin_siteurl = "{$a['siteurl']}"; /*Set the output code*/ $exampleplugin_shortcode_output = ""; $exampleplugin_shortcode_output .= '<p>Access the site with the following link: <a href="'.$exampleplugin_siteurl.'" target="_new">'.$exampleplugin_sitename.'</a></p>'; /*Return the output code*/ return $exampleplugin_shortcode_output; |
The last step is to close our function and register the shortcode with WordPress.
1 2 3 |
} /*Register the shortcode*/ add_shortcode( 'exampleplugin', 'exampleplugin_shortcode' ); |
Modify this template to fit whatever functions you want to preform.
Recent Comments