Support

Account

Home Forums Front-end Issues Send emails multiple recipents

Unread

Send emails multiple recipents

  • Hello,

    I am currently trying to configure a Contact Form 7 form to send emails to multiple recipients based on selected WooCommerce products. Each product has an ACF field (of type email) associated with it, and I would like the email to be sent to these addresses based on the selected products in the front end.

    I have implemented the following code in the functions.php file, but it doesn’t seem to work as expected. The email is sent to the recipient specified in the form configuration, but not to the email addresses associated with the selected products.

    Here’s the code I am using:

    // Retrieve email addresses linked to selected products
    add_action('wpcf7_before_send_mail', 'send_to_multiple_recipients');
    function send_to_multiple_recipients($contact_form) {
        if ($contact_form->id() == '1e5363b') {  // Replace with your form ID
            $submission = WPCF7_Submission::get_instance();
            
            if ($submission) {
                $posted_data = $submission->get_posted_data();
                $selected_products = isset($posted_data['product-selection']) ? $posted_data['product-selection'] : array();
    
                $recipients = array();
                foreach ($selected_products as $product_name) {
                    $product = get_page_by_title($product_name, OBJECT, 'product');
                    if ($product) {
                        $product_email = get_field('partnersz1_email', $product->ID);
                        if ($product_email) {
                            $recipients[] = $product_email;
                        }
                    }
                }
    
                if (!empty($recipients)) {
                    $mail = $contact_form->prop('mail');
                    $mail['recipient'] = implode(',', $recipients);
                    $contact_form->set_properties(array('mail' => $mail));
                }
            }
        }
    }
    
    // Automate product options generation
    add_shortcode('product_selection', 'generate_product_selection');
    function generate_product_selection() {
        $products = wc_get_products(array('limit' => -1));
        $output = '<select name="product-selection" multiple>';
        
        foreach ($products as $product) {
            $output .= '<option value="' . $product->get_name() . '">' . $product->get_name() . '</option>';
        }
        
        $output .= '</select>';
        return $output;
    }

    I would appreciate any guidance or suggestions to resolve this issue so that the email can be sent to the selected product addresses as intended.

    Thank you for your assistance!

    Best regards,

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.