No problem! Anyone using this should use the following code and not the code in my other reply, as it wasn’t PHP 8 friendly.
class WPCF7_SelectedCitiesHandler {
public function __construct() {
// Hook into Contact Form 7 mail sent action
add_action('wpcf7_mail_sent', [$this, 'handle_mail_sent']);
// Hook into MailChimp filter
add_filter('mc4wp_subscriber_data', [$this, 'filter_subscriber_data'], 10, 1);
}
public function handle_mail_sent($contact_form) {
// Add your handling logic here if needed, or leave it empty for now
error_log('Mail sent action triggered. Form ID: ' . $contact_form->id());
}
public function filter_subscriber_data(MC4WP_MailChimp_Subscriber $subscriber) {
// Add website subscriber tag
$subscriber->tags[] = 'Website Newsletter Subscriber';
// Retrieve the selected cities from the form submission directly
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
$selected_cities = !empty($posted_data['cities']) ? $posted_data['cities'] : [];
// Log the selected cities to ensure they are available
error_log("Selected Cities in filter_subscriber_data (From Form Submission): " . print_r($selected_cities, true));
// Check if selected cities exist and add them as tags dynamically
if (!empty($selected_cities)) {
foreach ($selected_cities as $city) {
// Add city name as a tag
$subscriber->tags[] = $city;
}
}
// Log the updated tags to confirm
error_log("Updated Tags: " . implode(", ", $subscriber->tags));
return $subscriber;
}
}
// Instantiate the handler
new WPCF7_SelectedCitiesHandler();