How to get the comment author name, email and website from his cookies?

I’m sure there are a lot of things where this function could be helpful. As for me I wanted the following: someone posts a comment on the website and when he goes to contact me page, the respond form would be filled with this data automatically

I’ve prepared a function for you which returns the array with all of the comment author data: his name, his email and his website (if specified of course).

You can insert this function to your current WordPress theme functions.php file.

function rudr_get_comment_author_data() {
	if( is_user_logged_in() )
		return false; // return false and exit the function if user is logged in
 
	$comment_author = array();
 
	foreach( $_COOKIE as $cookie_key => $cookie_value ) { // loop through all the cookies
 
		if ( strpos( ' ' . $cookie_key, 'comment_author_email' ) > 0 ) { // is email matches
        		$comment_author['email'] = urldecode( $cookie_value );
        	} elseif ( strpos( ' ' . $cookie_key, 'comment_author_url' ) > 0 ) { // if URL matches
        		$comment_author['url'] = urldecode( $cookie_value );
        	} elseif ( strpos( ' ' . $cookie_key, 'comment_author' ) > 0 ) { // else if author name
       			$comment_author['name'] = urldecode( $cookie_value );
       		}
 
	}
	return $comment_author; // the result array
}

Some notices:

Let’s look at the exaple with the respond form I was talking before.

<?php
	$author = rudr_get_comment_author_data();
?>
<form action="" method="POST">
	<input type="text" name="name" value="<?php if( isset( $author['name'] ) ) echo $author['name'] ?>" />
	<input type="email" name="email" value="<?php if( isset( $author['email'] ) ) echo $author['email'] ?>" />
	<textarea name="msg"></textarea>
	<button>Submit it</button>
</form>

The isset() is needed to avoid PHP notices like this Notice: Undefined index:. You can see them if WP_DEBUG=true in wp-config.php and one of the array elements is missing (comment author website for example).

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X