Creating an email link only if there's an email address

3 posts by 2 authors in: Forums > CMS Builder
Last Post: January 23, 2020   (RSS)

By CommonSenseDesign - January 23, 2020 - edited: January 23, 2020

Hi, there.

At the bottom of every page on my client's site, there's a list of names, each of which can be linked to an email address. Is there a way of only creating a link if an email address has actually been entered? i.e. leaving it as plain, unlinked text if a person doesn't have an email address.

If you scroll to the foot of this page, Ryan Daly - in the right column - doesn't want his email address listed, so it's been omitted. However, his name still appears as a link. www.tcmhomes.com/index.php

This is the code I'm currently using:

<?php foreach ($personnel_emailsRecords as $record): ?>
<?php echo htmlencode($record['title']) ?> - <a href="mailto:<?php echo htmlencode($record['email_address']) ?>"><?php echo htmlencode($record['name']) ?></a>
<?php endforeach ?>

Is there a solution, please?

By Deborah - January 23, 2020

Hi, CommonSenseDesign.

You believe you just need an "if" and "else" statements.

Give this a try:

<?php // if email address, show this
 if ($record['email_address']): ?>
<?php echo htmlencode($record['title']) ?> - <a href="mailto:<?php echo htmlencode($record['email_address']) ?>"><?php echo htmlencode($record['name']) ?></a>

<?php // if no email address, show this
 else: ?>
<?php echo htmlencode($record['title']) ?> - <?php echo htmlencode($record['name']) ?>
<?php endif ?>

By CommonSenseDesign - January 23, 2020

That works perfectly, thank you! http://www.tcmhomes.com/