Get Post ID within wp_set_comment_status hook

I am trying to update meta_value whenever I manually approve a comment inside the WordPress dashboard. I could not figure out how to do it dynamically, but it is working when I manually add a post ID:

add_action( 'wp_set_comment_status', 'average_ratings', 10, 2 );
function average_ratings( $comment_ID, $comment_status ) {
    if ( $comment_status == 'approve' ) {
        function average_ratingfn() {
            global $wpdb;

            $post_id = '208';  

            // bla bla bla
        }
        $commentar = average_ratingfn();
        add_post_meta( '208', 'overall', $commentar );   
    }
} 

How can I replace 208 with get_the_ID()?

Solutions Collecting From Web of "Get Post ID within wp_set_comment_status hook"

You should consider removing the average_ratingfn() function definition out of there and call it with an input argument for the post ID.

You can try to fetch the comment object with (untested):

$comment = get_comment( $comment_ID );

and then make sure it’s not null or you have an actual comment object with:

if( $comment instanceof \WP_Comment )
    $post_id = $comment->comment_post_ID;

You should be able to get the comment_post_ID field from that object.

I think you could also use the hooks within the wp_transition_comment_status() function, where the comment object is among the input arguments.

For example the hooks:

  • comment_{$new_status}_{$comment->comment_type}

  • comment_{$old_status}_to_{$new_status}

  • transition_comment_status