You cannot insert the do_action()
inside the class like that, it’s gonna give you a fatal error.
Instead you could use an array $skins
to store all the skin functions (as closures), and the magic method _call()
to call them:
class skinclass {
private $skins = array();
function __construct() {
$this->skins = apply_filters( 'add_skin', $this->skins );
}
function __call( $name, $post ) {
if(isset($this->skins[$name]))
return $this->skins[$name]( $post );
}
}
As you can see I used apply_filters()
to be able to add skins on initializazion, and then the__call
is gonna check if the skin exists and, if so, execute it.
So now to add a skin you add a filter that modifies the $skins
property:
// add skin1
add_filter( 'add_skin', function( $skins ){
$skins['skin1'] = function( $post ) {
$skin1 = '<article class="skin1-holder">';
$skin1 .= '<h2 class="skin1-title">'. get_the_title() .'</h2>';
$skin1 .= '<div class="skin1-excerpt">'. get_the_excerpt() .'</div>';
$skin1 .= '</article>';
return $skin1;
};
return $skins;
});
// add skin2
add_filter( 'add_skin', function( $skins ){
$skins['skin2'] = function( $post ) {
$skin2 = '<article class="skin2-holder">';
$skin2 .= '<h2 class="skin2-title">'. get_the_title() .'</h2>';
$skin2 .= '<div class="skin2-excerpt">'. get_the_excerpt() .'</div>';
$skin2 .= '</article>';
return $skin2;
};
return $skins;
});
Wait, but what about retrieving the skins list? Well, we can add a method to the class to do that, so inside the class you can add:
function get_skins() {
return array_keys($this->skins);
}
Ok so now to use the class you need to get an instance:
$skinObj = new skinclass();
And the rest is very similar to your code:
// get skin function in plugin
$skins = $skinObj->get_skins();
// to output skin in a drop down list
foreach ($skins as $skin_name) {
echo "$skin_name\n";
}
// output skin in front end
$func="skin1";
echo $skinObj->$func( $post );