achilles283
5/19/2014 - 10:20 AM

OO Shortcodes

OO Shortcodes

<?php

class My_Shortcode extends Shortcode {
  public function main($atts, $content) {
    echo "This is a really easy way to add shortcodes!";
  }
}
$My_Shortcode = new My_Shortcode;
$My_Shortcode->add();

class Shortcode {
  /*
   * Main output for our shortcode
   *
   * Execute our method - $main - and catch its output in a buffer
   * Return the output for WP to display
   *
   * @return string
   */
  public function output($atts = array(), $content = null) {
    ob_start();

    if (method_exists($this, 'main')) {
      $this->main($atts, $content);
    } else {
      echo self::error("No function provided!");
    }
    
    $output_string = ob_get_contents();
    ob_end_clean();
    return $output_string;
  }

  /*
   * Return an error string prefixed with the class name
   * for debugging
   *
   * @param string $msg
   * @return string
   */
  public function error($msg) {
    return get_class($this) . " error: {$msg}";
  }

  /*
   * Register our shortcode with WordPress
   * Either using $shortcode as the name, or the actual class name
   *
   * @param string $shortcode
   */
  public function add($shortcode = null) {
    $shortcode = ($shortcode ?: get_class($this));
    add_shortcode($shortcode, array($this, 'output'));
  }

  /*
   * Return a partial template from our shortcodes directory
   *
   * @param string $partName
   * @return string
   */
  public function get_shortcode_part($partName) {
    $shortcodeDirectoryName = strtolower(get_class($this));
    $template = locate_template("lib/shortcodes/{$shortcodeDirectoryName}/{$partName}.php");
    return $template;
  }
}