WordPress.org

Support

Support » Plugins and Hacks » Hacks » [Resolved] Increment a Counter after Comment is published

[Resolved] Increment a Counter after Comment is published

  • I am trying to create a plugin or function that increments a counter in the usermeta table for the comment author that I use in other parts of my site. Basically, I need a count of the total number of comments per user, and rather than doing a bunch of Database queries to figure it out, I wanted to add an action every time a comment was submitted that updates the comment count.

    I have never written a plugin before and I am having a hard time understanding what data gets passed to my function when I use:
    add_action (‘comment_post’, ‘MY_FUNCTION_NAME’);
    where “MY_FUNCTION_NAME” is the name of the function that I want to run.

    Normally, when I need to do some WP Hacking, I can figure it out by reading the documentation, but there doesn’t seem to be much for this. All I really need to know is how to determine (inside the function) what the user_id of the comment author is.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Inside your function do the following..

    global $commentdata;
    $the_user_id = $commentdata['user_id'];
    
    // $the_user_id now holds the ID of the appropriate user

    Hope that helps..

    Hey Mark, thanks for the help. I am having an issue with code that you sent me here. Whenever I try to use $the_user_id, it is always a NULL value using the code above. Is there something I am missing here? When I do a var_dump of $commentdata, all of the proper values are present, so that part of the puzzle is fine, just not the other. Thanks.

    I have determined the issue. The array uses capital letters for the user ID, so your code should read this:

    global $commentdata;
    $the_user_id = $commentdata['user_ID'];//NOTE THE CAPITAL LETTERS HERE
    
    // $the_user_id now holds the ID of the appropriate user

    So now everything works and I am able to update my counter for a user. Thanks!

    Yes sorry my mistake, glad you were able to spot the error… 😉

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Increment a Counter after Comment is published’ is closed to new replies.
Skip to toolbar