1

I am developing a plugin for woocommerce payment gateway.

When I put the code of class definition inside the callback function who is fired by 'plugins_loaded',it works.

<?php
    add_action('plugins_loaded','WC_test_gateway_plugin');
    function WC_test_gateway_plugin{
        class my_gateway extends WC_Payment_Gateways{
            //code
        }
    }
?>

But when I put it into global scope, it will show that the WC_Payment_Gateways is undefined.

<?php
    class my_gateway extends WC_Payment_Gateways{
        //code
    }
?>

What's the difference between these 2 practices?

Is it a bad practice to put class definition inside callback function? Any better way for it?

  • plugins_loaded is meant to be used here, and you should make a file for my_gateway class and include it in your WC_test_gateway_plugin callback. – Samuel Elh Feb 10 '17 at 11:46
1

Use your class definition in a separate file, say in /your-plugin-dir/classes/my-gateway.php like usual:

    <?php
        class my_gateway extends WC_Payment_Gateways {
            //code
        }
    ?>

Then use this CODE to include the file on plugins_loaded action from your main plugin file:

    add_action('plugins_loaded', 'WC_test_gateway_plugin');
    function WC_test_gateway_plugin {
        require_once plugin_dir_path( __FILE__ ) . 'classes/my-gateway.php';
        // instantiate your class here or in your class file or anywhere after this function is called.
    }

Now you'll get access to WC_Payment_Gateways because by now WC_Payment_Gateways is defined, since WordPress fires plugin_loaded action hook only after all the plugins have loaded their main files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.