Skip to content

Instantly share code, notes, and snippets.

@iambriansreed
Last active October 26, 2016 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iambriansreed/02ff2d0fc49364e73961b7e6a57f1f5a to your computer and use it in GitHub Desktop.
Save iambriansreed/02ff2d0fc49364e73961b7e6a57f1f5a to your computer and use it in GitHub Desktop.
Shortcodes Base Class
<?php
/**
* Shortcodes Base Class
*
* Adds dynamically named shortcodes using a child class's functions.
* Shortcode will not be created for functions prefixed with an underscore (_);
* Prefix is optional (recommended).
*
*/
abstract class Shortcodes_Base {
private $shortcodes = array();
/**
* optional shortcode prefix
* @return string
*/
abstract public function _prefix();
function __construct() {
$functions = get_class_methods( get_called_class() );
$prefix = $this->_prefix() ? $this->_prefix() . '-' : '';
foreach ( $functions as $function ) {
if ( substr( $function, 0, 1 ) === '_' ) {
continue;
}
$shortcode_tag = $prefix . str_replace( '_', '-', $function );
$this->shortcodes[ $shortcode_tag ] = $function;
add_shortcode( $shortcode_tag, array( $this, '_loader' ) );
}
}
/**
* calls the shortcode related function
*
* @param array $atts
* @param null $content
* @param string $tag
*
* @return string
*/
function _loader( $atts = array(), $content = null, $tag = '' ) {
if ( ! array_key_exists( $tag, $this->shortcodes ) ) {
return '';
}
$function_name = $this->shortcodes[ $tag ];
ob_start();
call_user_func( array( $this, $function_name ), $atts, $content );
return ob_get_clean();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment