WordPress function to send emails with attachment extracted from ACF (Advanced Custom Field)

112 views Asked by At

I'm creating a feature to send notification emails when an article is first published. There must be an attachment inside the email.

The part of code is:

function send_mail_post($new_status, $old_status, $post) {
    
    if ($new_status === 'publish' && $old_status !== 'publish') {


        // Attachment file
        $attachments = array(
            'attachment_1' => WP_CONTENT_DIR . '/themes/img/test.png',
        );

        // Send mail with attachment
        wp_mail($destinatario_email, $oggetto_email,$email_message, $intestazioni_email, $attachments);
    }
}

// Connect function to hook transition_post_status
add_action('transition_post_status', 'send_mail_post', 10, 3);

The system works by setting the file from URL statically:

$attachments = array(
'attachment_1' => WP_CONTENT_DIR . '/themes/img/test.png',
);

the email is sent with the attachment. The problem is that I can't extract the value from the custom field (created with ACF advanced custom field):

$attachment = get_field('attachment_1', $post->ID);

as it returns nothing. How can they change so that I can extract the URL from the custom field?

The custom field is already set to return the output value as a URL.

Thank you Roberto

1

There are 1 answers

0
Valerio Porporato On

transition_post_status is executed before meta data are saved, so get_field('attachment_1', $post->ID), at this point, returns NULL. I suggest you to add another action (acf/save_post) inside your callback function so that you can call another callback function later, at a time when the data has already been saved in the database. Your code can be rewritten as

function send_mail_post($new_status, $old_status, $post)
{

    if ($new_status === 'publish' && $old_status !== 'publish') {

        add_action('acf/save_post', function ($post_id) {
            $attachments = array(
                'attachment_1' => get_field('attachment_1', $post_id)
            );
            $destinatario_email = '[email protected]';
            $oggetto_email = 'your subject';
            $email_message = 'your message';
            $intestazioni_email = 'your headers';

            wp_mail($destinatario_email, $oggetto_email, $email_message, $intestazioni_email, $attachments);
        }, 10);
    }
    
}
add_action('transition_post_status', 'send_mail_post', 10, 3);