Wordpress plugins - divide in (OOP) Classes
So, i am developing a Plugin, and I am using a main Class so it can be more easily managed:
class MyPlugin{
function __construct(){
//my add_actions here
add_action('template_redirect', array($this, 'template_redirect'));
}
//my_class_methods here
function template_redirect(){}
}
Up until now, this is all working just fine. But as the plot thickens, I need to add more and more complexity in the plugin so I would like to do something like:
- create a new Class Comment
- in MyPlugin's __construct instantiate $comment = new Comment()
delegate, in my template_redirect(), an action to a method in $comment like:
add_action('wp_insert_comment', array($this->comment,'wp_insert_comment'));
or:
- create a new Class Comment
- in MyPlugin's __construct instantiate $comment = new Comment()
- in my Class 开发者_如何学编程Comment's __construct add the action to it's method
comment_method
:
add_action('wp_insert_comment', array($this, 'comment_method'));
Is this even possible? in either way, my behaviour isn't being called. Thanks for your help
Yes, it's possible, but you should probably add most actions and filters with the plugins_loaded
hook rather than using the template_redirect
hook, which probably is not called at all when a comment is posted (the form goes to wp-comments-post.php, wordpress deals with request, then redirects the user back to the page where the comment form was before the template is needed.)
class MyPlugin{
function __construct(){
add_action("plugins_loaded", array($this,"_action_plugins_loaded"));
}
function _action_plugins_loaded(){
//add actions & filters here...
}
}
精彩评论