-
-
Save jimboobrien/11e28a05a898ebefc3e8d353466bfcd1 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.
This file contains hidden or 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 | |
/** | |
* 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