Add PDF as E-Mail Attachment based on Subject

Hi, we were looking for a very simplistic code, that is not based on a Plugin specifically, but rather all E-Mails sent through the query. We’re now using this code.

Explanation

In $subject add specifically which subject line should be used. This needs to be an exact match.

In $pdf_id add the media library item number/ID of the PDF you want to attach.

Now, if an E-Mail with your exact-match subject is sent, the PDF with the ID x will be attached to it.

// Function to attach a PDF or document from the media library based on email subject
function attach_pdf_based_on_subject( $args ) {
    $subject = 'This needs to be an exact match.';
    $pdf_id = 123;

    // Check if the email subject matches your criteria
    if ( strpos( $args['subject'], $subject ) !== false ) {
        if ( $pdf_id ) {
            $args['attachments'] = array( get_attached_file( $pdf_id ) );
        }
    }

    // Return the modified email arguments
    return $args;
}
add_filter( 'wp_mail', 'attach_pdf_based_on_subject' );

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *