How to Include WordPress Site Name in wp_mail Subject Line

I’m working on a contact form and need to dynamically add my WordPress site’s name to the email subject. I want the subject to show up as “Contact from [my site name]” but I’m having trouble getting the site title to display properly.

Here’s what I’ve tried so far:

// form data from contact form
$userName = $_POST["contactName"];
$userEmail = $_POST["contactEmail"]; 
$message = $_POST["contactMessage"];
$siteName = '<?php echo get_bloginfo('name') ?>';

// email settings
$recipient = get_option('admin_email');
$emailSubject = "Contact from $siteName";
$emailHeaders = "From: $userEmail";
$emailBody = "Message from $userName:\n\n$message";

The site name isn’t showing up in the subject line. What’s the correct way to get the WordPress site title into a PHP variable for email purposes?

you’ve got your php tags tangled up. just change it to $siteName = get_bloginfo('name'); without the echo and the tags - you’re already in php!

Had the exact same problem building custom contact forms. You’re mixing HTML and PHP syntax wrong. Since you’re already in a PHP block, drop the PHP tags around get_bloginfo. Also check when you’re calling get_bloginfo - if it runs before WordPress loads completely, it’ll fail. I wrap my mail functions and hook them to wp_loaded or init to avoid this. One more thing - verify get_bloginfo(‘name’) actually returns what you want. Themes sometimes override it, or it’s empty if your WordPress settings aren’t configured right.

The problem is those unnecessary PHP tags inside your PHP block. Ditch the echo and tags - just use $siteName = get_bloginfo('name'); directly. I hit this same issue last year on a client’s contact form. Once you fix the syntax, add some error handling since get_bloginfo sometimes returns empty values depending on your WP setup. Try a fallback like $siteName = get_bloginfo('name') ?: 'Website'; so your subject line always has something. And make sure your contact form runs inside the WordPress environment where these functions actually work.