Skip to content

PHP – Convert ‘ShortCodes’ into Functions

WordPress has a great shortcode API that works really well. You an register a shortcode and a content manager can add it into the wysiwyg editor and that will invoke a function call. If you want to do the same just with PHP then here is a good start. I’m using shortcodes as variables in e-mail messages.

I’ve taken an object oriented approach this time to make it easier to set variables. But it can be done functionally instead.

class Shortcodes {
 
  // Variables
  private $firstname;
  private $lastname;
 
  public function __construct() {
 
    /* Set variables
     * Assume these will be dynamically set
     * Somewhere in the class
     */
    $this->firstname = 'Joe';
    $this->lastname  = 'Buckle';
 
    // Send dummy email
    $to      = 'joe@white-fire.co.uk';
    $subject = '{{firstname}}, Welcome to my site';   
    $body    = 'We would like to thank you by echoeing your first and last name. {{firstname}} {{lastname}}';
 
    mail($to, $this->shortcode_parse($subject), $this->shortcode_parse($body));
  }
 
  /*
   * Shortag format {{firstname}}
   */
  private function shortcode_parse($string) {
        return preg_replace_callback('#\{\{(.*?)\}\}#', function($matches) {
 
            // Shortcodes need to be delimited by a whitespace
            $whitespace_arr = explode(" ", $matches[1]);
 
            // Methods within this class are prefixed with shortcode_
            $method_name    = 'shortcode_'.array_shift($whitespace_arr);
 
            if(method_exists($this, $method_name)) {
 
                // If Method exists, convert shortcode to method
                return call_user_func_array(array($this, $method_name), $whitespace_arr);
            } else {
                return $matches[0];
            }
        }, $string);
  }
 
  // Our shortcode methods
  private function shortcode_firstname() {
    return $this->firstname;  
  }
 
  private function shortcode_lastname() {
    return $this->lastname;
  }
}
 
new Shortcodes();

About 

10 years + experience in web development working with lots of different technology.

Published inPHP

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *