WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Increment a Counter after Comment is published (5 posts)

  1. pkchrisjohnson
    Member
    Posted 3 years ago #

    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.

  2. Mark / t31os
    Moderator
    Posted 3 years ago #

    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..

  3. pkchrisjohnson
    Member
    Posted 3 years ago #

    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.

  4. pkchrisjohnson
    Member
    Posted 3 years ago #

    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!

  5. Mark / t31os
    Moderator
    Posted 3 years ago #

    Yes sorry my mistake, glad you were able to spot the error... ;)

Topic Closed

This topic has been closed to new replies.

About this Topic