How to add custom hooks to a custom plugin for Woo

2019-08-15 04:05发布

问题:

We have develop a custom plugin for Woocommerce payment integration and we need to add woocommerce hooks, in our plugin file without including it in Theme folder's function.php.

How can we Add custom hooks to our plugin that we can invoke from function.php file? is there any workaround for it?
(when we add custom woocommerce hooks and action code in function.php file in wordpress theme then code work fine but we need it in our custom plugin file.)

Any help will be highly appreciated.

回答1:

There is 2 kind of hooks: Action hooks and filter hooks.

An action hook is like a gate or a door in some code, that allow you to run some custom code, in a specific code location. It will be executed or "triggered", when the code that handle that door or gate runs. So it's event based.

Filter hooks are a bit different than action hooks. They are not use to trigger some custom code (not event based). They allow to alter or manipulate some existing code values, as strings, arrays, objects… So filter hooks have always at minima one argument to be manipulated and will always return that manipulated argument.


Create custom hooks in a plugin:

1) For action hooks: do_action() Wordpress function

do_action('woocommerce_my_custom_action', $some_variable, $another_variable );

2) For filter hooks: apply_filters() Wordpress function (where $value is the manipulated argument)

$value = apply_filters('woocommerce_my_custom_action', $value, $some_variable, $another_variable );

There is a bunch of documentation, tutorials and ressources on internet regarding hooks

Wordpress filter Vs. action

what is difference between action hook and filter hook in wordpress?

Wordpress Coding a custom action hook



回答2:

Your plugin should have its own functions in its own php files, it almost sounds like you are pasting the code into the theme's function.php file? And its being overwritten when the theme is updated? Is this what you are doing?

Please read the wordpress plugin development docs. https://developer.wordpress.org/plugins/intro/

If your plugin requires other plugins, there are several ways of making the user activate the other plugin(s) first: https://wordpress.stackexchange.com/questions/127818/how-to-make-a-plugin-require-another-plugin