Last active
August 29, 2015 14:01
-
-
Save soutar/539ab4421668df2dc31a to your computer and use it in GitHub Desktop.
OO Shortcodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment