Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active September 20, 2017 23:27
Show Gist options
  • Save wpscholar/4979758 to your computer and use it in GitHub Desktop.
Save wpscholar/4979758 to your computer and use it in GitHub Desktop.
Creating a class to handle a WordPress shortcode is overkill in most cases. However, it is extremely handy when your shortcode requires helper functions.
<?php
/**
* Creating a class to handle a WordPress shortcode is overkill in most cases.
* However, it is extremely handy when your shortcode requires helper functions.
*/
class My_Shortcode {
protected
$atts = array(),
$content = false,
$output = false;
protected static $defaults = array(
'class' => 'default-class',
);
public static function shortcode( $atts, $content ) {
$shortcode = new self( $atts, $content );
return $shortcode->output;
}
private function __construct( $atts, $content ) {
$this->atts = shortcode_atts( self::$defaults, $atts );
$this->content = $content;
$this->init();
}
protected function init() {
if( $this->content ) {
$this->output = $this->html_wrap( $this->content );
}
}
function html_wrap( $content ) {
return '<div class="'. esc_attr( $this->get_att( 'class' ) ) .'">'. $content .'</div>';
}
function get_att( $name ) {
return array_key_exists( $name, $this->atts ) ? $this->atts[$name] : false;
}
}
add_shortcode( 'my_shortcode', array( 'My_Shortcode', 'shortcode' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment