Comment appreciation with points

Navigation:

Description

In this tutorial we will add the myCred_send shortcode to your posts comments to allow users to give points to the comment author as a form of “Appreciation”.

Requirements

  • This tutorial requires myCred version 1.1 or higher.

Hooking into Comments

For this tutorial, we will be hooking into the comment text using the comment_text filter and append the myCred_send shortcode to the end of the text which will generate a simple button that users can click on to send 1 point to the comment author.

First, lets construct our custom filter:

add_filter( 'comment_text', 'my_custom_comment_text', 10, 2 );
function my_custom_comment_text( $comment_text, $comment )
{
	return $comment_text;
}

The WordPress codex tells us that the comment_text filter has two variables. The comment text itself and the comment object. Since we need to get the comment authors ID, we will need to call both of these variables.

The first thing our filter needs to do is to make sure that the current user is logged in, that the comment author is a registered member and that this is not the admin area. If this is not the case, we will return the text without the shortcode:

function my_custom_comment_text( $comment_text, $comment )
{
	// Make sure the current user is logged in
	if ( !is_user_logged_in() || $comment->user_id == 0 || is_admin() )
		return $comment_text;

	return $comment_text;
}

Note that if we do not include the is_admin() check, the appreciation button will be visible in the comment editor screen as well!

Next up we will load the myCred Settings Object and the current users ID. Once we have these we will need to make sure that neither the current user or the comment authors are “excluded” and that these two are not the same:

function my_custom_comment_text( $comment_text, $comment )
{
	// Make sure the current user is logged in
	if ( !is_user_logged_in() || $comment->user_id == 0 || is_admin() )
		return $comment_text;

	// Prep
	$mycred = mycred();
	$cui = get_current_user_id();

	// Make sure the current user is not the comment author
	if ( $cui == $comment->user_id ) return $comment_text;

	// Make sure the current user is not excluded
	if ( $mycred->exclude_user( $cui ) ) return $comment_text;

	// Make sure the comment author is not excluded
	if ( $mycred->exclude_user( $comment->user_id ) ) return $comment_text;

	return $comment_text;
}

Finally we will include the mycred_shortcode. Feel free to change the shortcode variables to something that suits you. In the below example, users will be able to send 1 point to the comment author and we call this action “Comment Appreciation”

Done

And that’s it. Place the code in your themes functions.php file and upload! Remember that if you are using an account that is excluded or if you are the comment author you will not be able to do any Comment Appreciation!

11