Notes

Creating WordPress shortcodes

Edit on GitHub

Web Development
2 minutes
 1// function that runs when shortcode is called
 2function my_awesome_function() { 
 3 
 4  // Things that you want to do. 
 5  $message = 'Hello world!'; 
 6   
 7  // Output needs to be returned
 8  return $message;
 9}
10
11// register shortcode
12add_shortcode('my_awesome_shortcode', 'my_awesome_function'); 

Add a shortcode in WordPress theme files

1<?php echo do_shortcode("[your_shortcode]"); ?>

NOTES

  • Prefixing the function names and shortcode names is a good idea. For example, consider the following function to load a stylesheet
1// Load the CSS file
2function add_plugin_stylesheet()
3{
4  wp_enqueue_style( 'country-site-selector', plugins_url(
5    'country-site-selector.css', __FILE__ ) );
6}
7add_action('wp_enqueue_scripts', 'add_plugin_stylesheet');

add_plugin_stylesheet has already been declared in another plugin i wrote. When i tried to use it in this plugin and activate it, it failed to do so because the function has already been used.. The function names need to be unique

Adding HTML/JS from the plugin

1function country_site_selector() {
2  ?>
3
4  <!-- BONGA! - i added this from plugin -->
5
6  <?php
7}
8add_action('wp_footer', 'country_site_selector');

is better than

1function country_site_selector() {
2  echo '<!-- BONGA! - i added this from plugin -->';
3}
4add_action('wp_footer', 'country_site_selector');

because when echoing from within PHP you have to add HTML as strings and don’t get any syntax highlighting.

jQuery vs. $

You can not use the $ shorthand when you enqueue in WordPress (for compatibility with other libraries)

var countrySelector = $( "#countrySelectionContainer" );

$(document).ready(function(){
  // code goes here
});

should be this

var countrySelector = jQuery( "#countrySelectionContainer" );

jQuery(document).ready(function(){
  // code goes here
});

Referencing plugin directory