I have a plugin class which contains a function spektrix_list_events()
class SpektrixPlugin {
public function __construct(){
add_action( 'init', array ( $this, 'init' ));
}
public function init()
{
add_action( 'spektrix_list_events', array ( $this, 'spektrix_list_events' ));
}
public function spektrix_list_events($getPrices = FALSE) {
$api = new SpektrixApiClient();
return $api->getAllEvents($getPrices);
}
}
$SpektrixEvents = new SpektrixPlugin;
add_action('init', array($SpektrixEvents, 'init'));
In a template file, I want to be able to call do_action(‘spektrix_list_events’) but can’t seem to get this working. I’ve tried following the advice here
Additional question – is using add_action() the recommended way to do this?
UPDATE:
The method is in fact being called but no results are returned. So how should one call a plugin class method which returns some output for display?
Some actions hooks need to be fired on specific events. Try this code:
I’ve tested this code and it works:
But …. I’ve been reading the WordPress documentation about
do_action()
and it says clearly thatdo_action()
will call the function/method but it won’t return anything. Quoteing WordPress aboutdo_action()
:So, you should check the apply_filters() function which works in a similar way that
do_action()
but can return the value returned by the called method or look for another implementation.do_action()
is not suitable to return values.An example usgin apply_filters:
Anyway, I think that this approach used to get data is no the appropiate. Although
apply_filters()
will work to get a value, as in the above example, the function is specially designed to filter a value, not to get one. I think the best you can do is have aget
method in your class used to get the value you want, then you can apply filters to that value or do actions with it.When working with classes and action, is a good practise, give an easy way to remove the action.
Using something like
add_action( 'init', array ( $this, 'init' ));
removing this action, can be done, but is far from easy.Another thing to consider, is that if you plain to use a plugin from theme, is a good idea insert some custom filters and actions hooks to customize the behavior of your plugin form themes.
So, in your case you can do something like this
After that, the class can be something like this:
And in your template file use just
or
Code is rough and untested, but should give you a direction to start.
If you want any function to work juhst hook it to your appropriate needs.I think in your case you want to execute function
spektrix_list_events()
. It is in class so use array in hookingadd_action('appropriate hook',array('SpektrixPlugin','spektrix_list_events'));
Hope this will help.