How to Add an Email Link in WordPress in 3 Easy Steps

Home » Snippets » How to Add an Email Link in WordPress in 3 Easy Steps

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

Would you like to make it easy for your website visitors to send you an email without having to copy and paste your email address? One way to do that is by adding an email link to your WordPress site. In this article, we’ll show you how to add an email link in WordPress so that your visitors can contact you with just a click of a button. It’s a simple process that can make a big difference in your user experience.

					function wpturbo_email_link_shortcode( $atts, $content = null ) {
    $email = antispambot( $content );
    return '<a href="mailto:' . $email . '">' . $email . '</a>';
add_shortcode( 'email', 'wpturbo_email_link_shortcode' );

Let’s break down this code snippet line by line.

The code begins with the declaration of a new function called wpturbo_email_link_shortcode(). This function will create an email link when it’s used as a shortcode in WordPress.

function wpturbo_email_link_shortcode( $atts, $content = null ) {

Within the function, we receive two parameters: $atts and $content. $atts stands for attributes, and it is an array used to store any attributes used when calling the shortcode. $content contains all the content within the shortcode’s opening and closing tags.

$email = antispambot( $content );

The antispambot() function is a built-in WordPress function used to protect email addresses from spam bots. We apply it to the $content variable to make sure spambots can’t extract email addresses from the HTML code. After applying the function to $content, we save it to a new variable called $email.

return '<a href="mailto:' . $email . '">' . $email . '</a>';

This line of code creates the email link. We use the $email variable to set both the target of the link and the text that displays to the user.

The href attribute of the <a> tag opens a new email message, and the mailto: protocol ensures that the user’s preferred email software opens the message.

We use the $email value again for the visible text of the link that appears on the front-end of the site.

add_shortcode( 'email', 'wpturbo_email_link_shortcode' ); 

The last line hooks up the shortcode.

The add_shortcode() function is a built-in WordPress function that defines shortcodes. We pass the shortcode’s name (’email’) as the first parameter and and the name of our shortcode function as the second parameter (‘wpturbo_email_link_shortcode’). When someone uses the shortcode [email] in a WordPress post or page, the wpturbo_email_link_shortcode() function is called, creating the email link.

Register an account to save your snippets or go Pro to get more features.