wordpresswoocommerceboilerplate

Class 'WC_Email' not found error when creating custom WooCommerce email in Boilerplate-based plugin


I am trying to add a custom email to WooCommerce. I've found several good tutorials on how to do so. All of them extend the WC_Email class to define their new email type. I am getting an error when trying to do so, saying the the class is not found.

Note: My plugin is created using Boilerplate, so it may load things in a different sequence or manner than that used by any of the tutorials I've found.

Other uses of WooCommerce hooks and filters are working fine, able to reach the WC functions. What could be stopping the class from extending? I assume that I am not referencing it correctly, or that it is not loaded at the time Boilerplate tries to use it. But I've spent several hours over a couple of days now, and I'm still stuck. Any assistance would be appreciated.

My Boilerplate top class has its standard function:

private function load_dependencies() {
.
. Additional requirements as defaulted by Boilerplate
.
        /**
         * The class responsible for defining the custom WooCommerce email 
         */
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'emails/class_wc_ready_for_pickup_email.php';

        $this->loader = new MyPlugin_Plugin_Loader();

    }

The ready-for-pickup class file says:

class WC_Ready_for_Pickup_Email extends WC_Email. <<<<< This is where the error occurs
{
    /**
     * Set email defaults
     *
     * @since 0.1
     */
    public function __construct() {

        // set ID, this simply needs to be a unique name
        $this->id = 'wc_ready_for_pickup';
.
. Additional code as shown in tutorials
.
}
...

The exact error is

Fatal error: Uncaught Error: Class 'WC_Email' not found in /Users/me/Local Sites/my-site/app/public/wp-content/plugins/my-plugin/emails/class_wc_ready_for_pickup_email.php on line 7

Solution

  • Looks like the class WC_Email is not available at the time you init your custom email class and extending it. Since I remember you should add email classes via a hook and not directly inside your class constructor:

    add_filter( 'woocommerce_email_classes', 'filter_woocommerce_email_classes' );
    function filter_woocommerce_email_classes( array $email_classes ): array {
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'emails/class_wc_ready_for_pickup_email.php';
    
        $email_classes['WC_Ready_for_Pickup_Email'] = new WC_Ready_for_Pickup_Email();
    
        return $email_classes;
    }