0
votes

I've created a new page in WordPress and set a custom made template as template for the new page.

In my template I'm doing some stuff like show a HTML content. After all worked fine I've decided to add a do_action in my custom template to sent an email via WooCommerce email client/class.

So I've set up a new email class and build a custom trigger in this class which triggers the email sending:

// Triggers for this email.
add_action( 'trigger_rated_email', array( $this, 'trigger' ), 10, 10 );

/**
     * Trigger the sending of this email.
     *
     * @param int $order_id The order ID.
     * @param WC_Order|false $order Order object.
     */
    public function trigger( $order_id, $order = false ) {
        $this->setup_locale();

        if ( $order_id && ! is_a( $order, 'WC_Order' ) ) {
            $order = wc_get_order( $order_id );
        }

        if ( is_a( $order, 'WC_Order' ) ) {
            $developer_id = get_post_meta( $order_id, 'developer_id', true );
            $developer    = get_userdata( $developer_id );

            $this->object                         = $order;
            $this->recipient                      = $developer->user_email;
            $this->placeholders['{order_date}']   = wc_format_datetime( $this->object->get_date_created() );
            $this->placeholders['{order_number}'] = $this->object->get_order_number();
        }

        if ( $this->is_enabled() && $this->get_recipient() ) {
            $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
        }

        $this->restore_locale();
    }

This add_action triggers the trigger() method in the email class which sends the email. To trigger the sending I've done this in my custom template PHP file:

do_action( 'trigger_rated_email', $order_id );

After saving it I've uploaded it to my server and called the page but there is no email sent to my email account.

So I've did a lot of checks to clarify if there is a problem in my email class:

  1. Triggered the email from an other page (not custom template) -> email gets sent
  2. Checked if there is an error in my debug.log -> no error

So what is the problem? I think there must be a problem in the custom template so my first thoughts are that the do_action is not called correctly because it don't knows the add_action from my class.

1

1 Answers

0
votes

After a lot of hours and a help from a good friend we've found the problem. The point is that when you want to sent email from a non WooCommerce page you need to initialize the WooCommerce mailer first.

So for all who wants to sent emails from a non WooCommerce page do this here:

WC()->mailer();
do_action( 'trigger_your_custom_email', $order_id );

In your custom WooCommerce email class do this here:

add_action( 'trigger_your_custom_email', array( $this, 'trigger' ), 10, 10 );