A shortcode to display the admin email of a WordPress website

This simple shortcode displays the administrator email address of a WordPress website. You can render the email address as plain text or as a mailto: link.

Usage

Display the plain email address
[hx_admin_email]

Display the email as a clickable "mailto" link
[hx_admin_email format="mailto"]

Shortcode

// Register a shortcode [hx_admin_email] with optional 'format' parameter to display admin email
function hx_admin_email_shortcode($atts) {
    // Define default attributes and merge with user-provided attributes
    $atts = shortcode_atts(
        array(
            'format' => 'plain', // Default format is 'plain' (just email text)
        ),
        $atts, // Attributes passed by the shortcode usage
        'hx_admin_email' // Shortcode name for context
    );

    // Retrieve the WordPress admin email address from the database
    $email = get_option('admin_email');

    // Check if the 'format' attribute is set to 'mailto'
    if ($atts['format'] === 'mailto') {
    
    // Return the email wrapped inside a mailto hyperlink safely escaped for HTML   attributes and content
        return '<a href="mailto:' . esc_attr($email) . '">' . esc_html($email) . '</a>';
    }

    // If format is not 'mailto', return the plain email address safely escaped for HTML output
    return esc_html($email);
}
// Hook the shortcode name 'hx_admin_email' to the above function
add_shortcode('hx_admin_email', 'hx_admin_email_shortcode');

Background

The hx_admin_email shortcode is a custom snippet that displays the administrator email address anywhere shortcodes are supported, such as in posts, pages, or widgets. This site uses the shortcode on our 404 page.

In WordPress, the administrator’s email is stored in the admin_email option, which is accessible in the dashboard at Settings > General > Administrator Email Address. The shortcode retrieves that value and allows optional formatting:

  • Plain text (default) – Shows just the email address as text
  • Mailto link – Wraps the email in a clickable mailto: hyperlink, making it easy for visitors to start an email directly from the page.

The use of esc_attr() and esc_html() ensures that the output is safe, preventing malicious code injection (XSS). This may seem unlikely for an admin-defined value, but it is a good habit to escape output anyway.

How to use

To manually install this shortcode, you can add it to functions.php in your theme. However, this is dangerous and we recommend using a plugin that allows you to create and manage custom bits of code without changing your theme files. Two plugins we recommend are Code Snippets and WPCode. Both have free versions that allow you to create custom shortcodes.

Reference

License

Feel free to remix this content for your website.

Licensed under CC BY 4.0

Leave a Reply