Automatically grab article author email

How can i automatically grab the author email of an article ?

The scenario is this: You have a form published inside an article, you need to send an email to the author whenever the form is submitted.

There are two ways to implement this, depending on your use case scenario:

  • store the email inside a field for future reference
  • grab the email address during the sending process, if you don't need to store it

 

Method 1: store the email

  • You will need to add a hidden field to your form. Let's assume that this will be named authorEmail
  • In the Default Value area of the field in question, add the following code:
      //<code>
      // Get a database connection.
      $db = JFactory::getDbo();
    
      // Get the current article ID from the URL.
      $articleId   = JFactory::getApplication()->input->getInt('id');
    
      // Setup the query.
      $db->setQuery("SELECT created_by FROM #__content WHERE `id`='".$db->escape($articleId)."'");
      $createdBy = $db->loadResult();
      if ($createdBy) {
        // Get the user based on the created_by column value.
        $user = JFactory::getUser($createdBy);
    
        // Return the email address.
        return $user->get('email');
      }
      //</code>
    
  • We will need to add the extracted email address to the recipients list to either User or Admin email configuration areas. Simply head to User or Admin email areas, and type in the field placeholder into the TO area (for example): {authorEmail:value}

 

Method 2: dynamically adjust the recipient

This method is useful if you do not wish to store the author email. The script would need to be placed in the PHP Email scripts tab, depending which email type will be used, in the Script called before the User Email is sent or Script called before the Admin Email is sent areas. We will assume that the Admin Email will be used:

  // Get a database connection.
  $db = JFactory::getDbo();

  // Get the current article ID from the URL.
  $articleId   = JFactory::getApplication()->input->getInt('id');

  // Setup the query.
  $db->setQuery("SELECT created_by FROM #__content WHERE `id`='".$db->escape($articleId)."'");
  $createdBy = $db->loadResult();
  if ($createdBy) {
    // Get the user based on the created_by column value.
    $user = JFactory::getUser($createdBy);

    // Change the recipient. $adminEmail['to'] contains the email address of the recipient.
    $adminEmail['to'] = $user->get('email');
  }

Was this article helpful?

Yes No
Sorry about that

You Should Also Read

How to store the submission in a file and send it through the email HOT

Retrieve author email address in Sobi2