Tom-Hayes
1/19/2017 - 7:09 PM

You can create your own shortcodes without the need of a plugin. These shortcodes can be used in pages and posts like so: [person name="John

You can create your own shortcodes without the need of a plugin. These shortcodes can be used in pages and posts like so: [person name="John Smith" image="/images/people/john-smith.jpg" size="large"] Add this code in your functions.php file located in your theme folder.

// Return a simple string
// [foobar]
function foobar_func( $atts ) {
  return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );


// Return a string with attributes
// [foobar foo="HelloWorld"]
function foobar_func( $atts ) {
  $a = shortcode_atts( array(
    'foo' => 'Default value here if no value passed to parameter',
  ), $atts );
  return "foo = {$a['foo']}"; // foo = HelloWorld
}
add_shortcode( 'foobar_atts', 'foobar_func' );


// Using the example above return some HTML on to the page/post including the parameters defined in the shortcode
// [person name="John Smith" image="/wp-content/themes/mytheme/images/people/john-smith.jpg" size="large"]
function person_shortcode($atts) {
  $person = shortcode_atts( array(
    'name' => '',
    'image' => '/wp-content/themes/mytheme/images/people/no-image.jpg',
    'size' => 'large'
  ), $atts );
  return "<div class='person'><h3>{$person['name']}</h3><img src='{$person['image']}' alt='{$person['name']}' class='{$person['size']}'/></div>";
}
add_shortcode('person', 'person_shortcode');