DevinVinson / WordPress-Plugin-Boilerplate

[WordPress] A foundation for WordPress Plugin Development that aims to provide a clear and consistent guide for building your plugins.
http://wppb.io
7.67k stars 2.25k forks source link

What about a nested actions and filters? #460

Open sailorsamoor opened 6 years ago

sailorsamoor commented 6 years ago

Hello. I have such piece of code:

function foo() { function bar() { ;;;;; } add_filter( 'some_of_filter', 'bar' ); } add_actions( 'plugin_loaded', 'foo' );

Which is the best practice for do that if I want to place all actions and filters into main class of WordPress-Plugin-Boilerplate?

Best regards, Vladimir.

dingo-d commented 6 years ago

Are you sure you can't use apply_filters() instead of bar() function inside your foo() method?

sailorsamoor commented 6 years ago

Emmm... And how it looks? That is what I do: I created a Loader-Class

class WC_Onpay_Payment_Gateway_loader {

public function __construct() {

}

/**
 * Set Onpay Gateway method into pay method list
 *
 * @since    1.0.0
 */
public function add_onpay_gateway_method( $methods ) {

    $methods[] = 'WC_Payment_Gateway_Onpay';
    return $methods;

}

 /**
 * Load WC_Onpay_Payment_Gateway class
 *
 * @since    1.0.0
 */
public function init_onpay_gateway() {

    require_once plugin_dir_path( dirname( __FILE__) ) . 'onpay-gateway/class-woocommerce-vvss-pack-onpay-gateway.php';

    add_filter( 'woocommerce_payment_gateways', array( $this, 'add_onpay_gateway_method' ) );

}

}

Then I load this Loader and run a actions:

/**
 * Define Onpay payment gateway
 *
 */
private function set_onpay_gateway() {

    $onpay_gateway_loader = new WC_Onpay_Payment_Gateway_loader();

    $this->loader->add_action( 'plugins_loaded', $onpay_gateway_loader, 'init_onpay_gateway', 0 );

}

I don't know, sorry, how can I do it another way - I read the method of Gateway load from docs.

dingo-d commented 6 years ago

This looks odd to me, but if it works ¯\(ツ)\

You are using the plugins_loaded hook to ensure all the plugins are loaded so that you have available WooCommerce methods? Because it seems like an extra step to me. Did you try just using

    $this->loader->add_filter( 'woocommerce_payment_gateways', $onpay_gateway_loader, 'add_onpay_gateway_method', 0 );

And perhaps changing the priority from 0 to a later number so that you are sure that WooCommerce's filters are executed before your plugin?

sailorsamoor commented 6 years ago

Well, I did it: /**

It works but I'll check. There are two or more filters that I have to insert. Thanks again).