I would like feedback on my work, because I know this is not perfect at all. I got it working, so it's already fine, but I'm pretty sure there are better way of doing it.
So what I've done is a basic Facebook-like feature which allows anyone to simply click on the Like button, the pages refreshes and the Like button then becomes Like (1). Then Like (2)... You know.
An example, you will ask? Voilà
Don't worry, it's in French, but I try to code in English so I can get help from you guys. Thus, you should actually look for J'aime (1) instead.
Here's how I did.
- Created a 'comment_like' Integer field in 'wp_comments' table.
- Added in my theme's 'functions.php', the following form:
<form action="<?php echo home_url( '/wp-content/themes/twentyten/wp-likes-post.php' ); ?>" method="post" class="like-button" name="like-button"> <input type="hidden" id="liked_comment_ID" name="liked_comment_ID" value="<?php comment_ID(); ?>" /> <input type="submit" class="like-button" id="submit" name="submit" value="Like<?php $comment_ID = get_comment_ID(); $likes = get_comment($comment_ID)->comment_likes; if ($likes==0) echo ''; else echo ' (' . $likes . ')'; ?>" /> </form>
- Created the form action file 'wp-likes-post.php':
<?php $liked_comment_ID = $_POST['liked_comment_ID']; $db = mysql_connect('localhost', 'LOGIN', 'PASSWORD'); mysql_select_db('DATABASE',$db); $sql = "UPDATE wp_comments SET comment_likes = comment_likes +1 WHERE comment_ID = $liked_comment_ID"; $req = mysql_query($sql) or die('SQL Error!'.$sql.''.mysql_error()); mysql_close(); $ref = $_SERVER['HTTP_REFERER'] . '#comment-' . $liked_comment_ID; header( 'refresh: 0; url='.$ref); ?>
I'm happy that it works, but unsatisfied with my methods.
First, how do I use $wpdb to connect to the database and update the field for the specified comment? Please don't tell me to look at the Codex; I assure you, I did. However, having the form action script in the themes folder doesn't not seem to recognize the $wpdb... What I mean here is that when I put the script (test version) in the header, it worked, but the same script in my theme's folder did not.
So, what exact code should replace the UPDATE mySQL part of my form action script?
Second, what should I write to get a quick redirect after my script? Here again, I read the wp_redirect() Codex page, but to no avail. The current PHP redirect takes a bit of time to reload... I don't know anything about AJAX, would someone know the answer on how to do the database update right on the click (no refresh)?
That's pretty much it for now. Let me know what you think of it.
Thank you for your cooperation.
PS: I'm not good in PHP.