1

with some help I manage to create a plugin to attach, on the finished order email, an invoice.

        add_filter( 'woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3);
    
    function attach_terms_conditions_pdf_to_email ( $attachments, $status , $order ) {
        $allowed_statuses = array( 'customer_completed_order' );
    
        if( isset( $status ) && in_array ( $status, $allowed_statuses ) ) {
            $pdf_name = get_post_meta( get_the_id(), 'email_fatura', true );
            $pdf_path = get_home_path() . '/Faturas/GestaoDespesas/' . $pdf_name;
            $attachments[] = $pdf_path;
        }
    
        return $attachments;
    }

This code is to check on the order meta for "email_fatura" (translated "email_invoice"), and get the value of this field. This value takes the path root /Faturas/GestaoDespesas/ORDER123.pdf and attach the pdf to the email.

However, the problem is when there isn't a field "email_fatura", it stills attachs a file called "GestaoDespesas", that comes from /Faturas/**GestaoDespesas**/

For those who know PHP I assume that it is easy to fix this.

Thank you in advance for any kind of help.

Ruvee
  • 8,611
  • 4
  • 18
  • 44
TiagoSantos
  • 127
  • 8

1 Answers1

1

I would first check whether the field is empty or not, if it is then just return:

add_filter( 'woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3);

function attach_terms_conditions_pdf_to_email ( $attachments, $status , $order ) {
    $allowed_statuses = array( 'customer_completed_order' );
 
    $pdf_name = get_post_meta( get_the_id(), 'email_fatura', true );

    if ( empty($pdf_name) ){
        return;
    }

    if( isset( $status ) && in_array ( $status, $allowed_statuses ) ) {
        $pdf_name = get_post_meta( get_the_id(), 'email_fatura', true );
        $pdf_path = get_home_path() . '/Faturas/GestaoDespesas/' . $pdf_name;
        $attachments[] = $pdf_path;
    }

    return $attachments;
}
Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • It worked! When there isn't a meta field called "email_fatura" it doesn't attach anything. Thank you very much for your help! – TiagoSantos Jan 27 '21 at 11:41