WordPress : Send Mail to Admin when user comes to 404 page

Sending mails to admin is very easy in wordpress by using a inbuild wordpress function wp_mail.
But if you want to send a mail to wordpress admin when user comes to 404 page then you can use below simple code.

Sending mail when user comes to 404 page in wordpress
This code can be added in your wordpress theme’s functions.php file or in custom plugin. You need to write a custom plugin for the same. Please let me know if you need any help to write a custom plugin. As i am using a custom plugin for my wordpress websites and that custom plugin have lots of functions and wordpress hooks that makes my life easy and simple.

Below script checks the referring link of your website, and then sends an email to the webmaster/wordpress admin.

if (!function_exists('email_admin')){
	function email_admin(){
		$message = "";
		if(isset($_SERVER['HTTP_REFERER'])){
			$message .= "User came from: ".$_SERVER['HTTP_REFERER']."\r\n";
		}
		$ipAddress 		= 	$_SERVER["REMOTE_ADDR"];
		if($ipAddress!=''){
			$message .= "Track User Data: http://www.ip-adress.com/ip_tracer/".$ipAddress."\r\n";
		}
		$browser 		= 	$_SERVER['HTTP_USER_AGENT'];
		if($browser!=''){
			$message .= "Browser: ".$browser."\r\n";
		}
		$message.="Page URL they tried to access was: ".home_url().$_SERVER['REQUEST_URI']."\r\n";
		$admin_email 	= 	get_option('admin_email');
		$subject		=	'404 Error at '. home_url();
		//echo $subject;	echo $message; die;
		@wp_mail($admin_email,$subject,$message);
	}
	
	function mail_me_errors(){
		global $wp_query;
		if ($wp_query->is_404){
			email_admin();
		}
	}
	add_action('get_header', 'mail_me_errors');
}

By Vaseem Ansari

I’m Vaseem, a Software Engineer by Profession, a Traveler, a Foodie by Heart and the founder of VaseemAnsari.com. I started traveling from college days and it has become a part of me now. So when ever I happen to get a chance I pack my bag and am on the roads. You can follow me on these social networks Facebook, Twitter, Google+ and Linkedin.

Leave a comment

Your email address will not be published. Required fields are marked *