• Resolved houseofhands

    (@houseofhands)


    Is there a way to set the current user email address as the From header, without using a field?

    Situation:
    I have several forms especially for logged-in users and I don’t want to bother them to fill out fields with personal info every time. To identify them I want the From field to contain the current users email address.

    I tried this:
    /* —————————
    function filter_email_headers( $headers, $email, $form, $fields ) {
    // Add a copy to client

    $current_user = wp_get_current_user();
    $email = $current_user->user_email;

    $headers[] = ‘From:’ . $email;

    return $headers;
    }
    add_filter( ‘af/form/email/headers/key=FORM_KEY’, ‘filter_email_headers’, 10, 4 );
    /* —————————

    Any pointers? Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author fabianlindfors

    (@fabianlindfors)

    Hi!

    Looking at this my implementation of email headers is not optimal. It’s a bit hard to edit existing fields such as from because they are stored in a continuous array when it should really be an associative one.

    Here’s one way to work around it. Haven’t had a chance to test it but the basic idea is to find the “From” header and replace it with a new one:

    function filter_email_headers( $headers, $email, $form, $fields ) {
      foreach ( $headers as $i=>$header ) {
        if ( false !== strpos( $header, 'From:' ) ) {
          // Add a copy to client
          $current_user = wp_get_current_user();
          $email = $current_user->user_email;
          $header[ $i ] = 'From: ' . $email;
        }
      }
    
      return $headers;
    }
    add_filter( ‘af/form/email/headers/key=FORM_KEY’, ‘filter_email_headers’, 10, 4 );
    

    I’m going to think about how to fix this ??

    Thread Starter houseofhands

    (@houseofhands)

    Hi Fabian,

    Thanks for your response.
    The code does not work. It does not change the From header.

    My main goal was to identify the current logged in user, so I used the filter af/form/email/content (source: https://advancedforms.github.io/filters/af-form-email-content/).

    The code below I’m using now meets my goal.

    /* Identify user sending this form - put this in functions.php
    ------------------------------------------------------------------ */
    function display_name_in_content( $content, $email, $form, $fields ) {
    	// Add some extra text to the end of the content
        $current_user = wp_get_current_user();
        $displayname = $current_user->display_name;
        $content .= ' This message is send by ' . $displayname;
        
        return $content;
    }
    add_filter( 'af/form/email/content/key=FORM_KEY', 'display_name_in_content', 10, 4 );

    Thanks again!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Set current user email as $headers From’ is closed to new replies.