So it’s been a while since I’ve done a screencast, but here it is, number 2! In this screencast I’ll show you how to create a comment preview section in WordPress which dynamically loads user information and updates as you type! For it I use the trusty jQuery library and a little bit of PHP code to spice things up. See below the video for the code used, and enjoy!
The comments.php code:
<div id="preview-comment"> <br /> <h4>Comment Preview:</h4> <div></div> <li> <div id="div-comment-12"> <div> <?php if(is_user_logged_in()){ global $current_user; get_currentuserinfo(); } ?> <img id="avatar-preview" width="64" height="64" src="<?php if(!is_user_logged_in()){ ?>http://www.gravatar.com/avatar/<?php }else { echo "http://www.gravatar.com/avatar/" . md5($current_user->user_email); } ?>" alt="Avatar"> <cite><a rel="external nofollow" href="#"><?php if(!is_user_logged_in()){ ?>Mr Nobody<?php }else{ echo $current_user->user_firstname; } ?> </a></cite><span>says:</span> </div> <div> <a><?php wp_reset_query(); echo gmdate("F j, Y \\a\\t g:i a ") ?></a> </div> <p>This is an example comment.</p> <div> <a>Reply</a> </div> </div> </li> <br /> </div>
And the Javascript:
<script type="text/javascript">// <![CDATA[ $(document).ready(function(){ $("#commentform input, #commentform textarea").focus(function(){ $("#preview-comment").slideDown(); }); $("#commentform input, #commentform textarea").blur(function(){ if($("#commentform #author").val()=="" && $("#commentform #email").val()=="" && $("#commentform #url").val()=="" && $("#commentform #comment").val()==""){ $("#preview-comment").slideUp(); } }); $("#commentform #author").keyup(function(){ $("#preview-comment a.url").text($("#commentform #author").val() + " ") }); $("#commentform #author").blur(function(){ $("#preview-comment a.url").text($("#commentform #author").val() + " ") }); $("#commentform #email").blur(function(){ $("img#avatar-preview").load('/scripts/md5.php?m=' + $("#commentform #email").val()); }); $("#commentform #url").keyup(function(){ $("#preview-comment a.url").attr('href', $("#commentform #url").val()); }); $("#commentform #url").blur(function(){ $("#preview-comment a.url").attr('href', $("#commentform #url").val()); }); $("#commentform #comment").keyup(function(){ $("#preview-comment p").text($("#commentform #comment").val()) }); $("#commentform #comment").blur(function(){ $("#preview-comment p").text($("#commentform #comment").val()) }); }); // ]]></script>
And the md5.php file:
<script type="text/javascript"> <?php $hash = md5($_GET['m']); ?> $("img#avatar-preview").attr('src','http://www.gravatar.com/avatar/<?php echo $hash ?>'); </script>
Note: Bear in mind that changing the comments form will involve changing the code above.
Comments
One response to “Screencast #2 – Creating a Comment Preview in WP”
Thats great, thanks so much for the code