The comment_post
hook is called with a $comment_id
as the first argument.
You can see why your function is failing. Same goes for the edit_comment
hook.
Simply add the following at the beginning of your business function:
if ( !is_object( $comment ) )
$comment = get_comment( $comment );
Do use a custom SQL query for comment metadata retrieval, as right now, with what you have there, you’ll end up querying the database for each and every comment. Moreover, I would additionally suggest using the built-in SUM
and AVG
MySQL functions to avoid the extra loops in PHP.
SELECT SUM(`meta_value`), AVG(`meta_value`)
FROM `{$wpdb->commentmeta}`
WHERE `meta_key` = 'rating'
AND `comment_id` = '$sanitized_comment_id';