My organization wants to remove ALL email addresses from our website and replace them with links that go to a contact form which will generate an email to the corresponding person. The email address should NOT appear on the website, not even let’s say base64 encoded. The contact form URL should contain a unique ID that corresponds to an entry in a db table (or a custom post type) where that ID is associated with the correct email address.
Find the answer below, or more details in Reddit comments section.
It can be cleaner than this, but the quickest way to do it without a lot of work is:
Step 1:?Store all emails inside an option as an array. Let’s name the option “mf_custom_email_list”, make sure it’s not autoloaded and each email has an ID as key. ( make sure the data is saved as a serialized php array ), it’s better to update using WordPress core functions, eg:
Step 2: Update all the mailto links to redirect to a contact page but make sure to add a query param to reflect the email ID, it can be “to” for example, so the url will look something like <a href=”https://yourwebsite.com/contact?to=22″>.
Step 3:?Install?Mega Forms, create your contact form and add a hidden field, set the hidden field value to something like this {mf:misc get="to"} as it appears in the screenshot. Then under actions tab, add an “email” action and set the “to” field to pull the email from the hidden field you created, it will look something like this {mf:fields 6} where number 6 is the ID of the field. See the attached screenshot for examples.
Step 4:?Now add a snippet that will replace the provided ID with the actual email server side to make sure emails are not exposed anywhere. Here is the snippet you can use
add_filter('mf_posted_data_before_process', 'mf_modify_email_field', 10, 3); function mf_modify_email_field($posted, $form, $context) { $the_hidden_field_id = 6; // Check if the field with ID 6 exists in the posted data if (isset($posted['fields'][$the_hidden_field_id])) { // Get the submitted value $submitted_value = mfpost($the_hidden_field_id, $posted['fields']);
// Get the custom email list from WordPress options $custom_email_list = get_option('mf_custom_email_list', array());
// Not valid data format, initialize an empty array if (!is_array($custom_email_list)) { $custom_email_list = array(); error_log("mf_custom_email_list option is neither an array nor a valid serialized array."); }
// Check if the submitted value exists as a key in the custom email list if (isset($custom_email_list[$submitted_value])) { // Replace the submitted value with the corresponding email $posted['fields'][$the_hidden_field_id] = $custom_email_list[$submitted_value]; } else { // If the key doesn't exist, you might want to handle this case // For example, you could set a default email or log an error error_log("No email found for key: " . $submitted_value); // Optionally set a default email: // $posted['fields'][$the_hidden_field_id] = '[email protected]'; } } return $posted; }