Rewrite comment form post ID on submit

I have a WordPress comment form, with a custom field (added with the Advanced Custom Field plugin) where the visitor can chose from a options (these are page IDs). When submitting the form, I want this select value to replace the comment_post_ID that by default adds the current page ID.

What I'm trying to achieve is having a global comment form on just one page and then for the visitor to select a page (in our case, these are medical treatments) and then on submit, the comment is attached to the selected page, rather than the page the comment form is on.

I have tried the preprocess_comment filter, which works fine if I hardcode the ID:

function overwrite_comment_post_id( $commentdata ) {
    $commentdata['comment_post_ID'] = '1562';
    return $commentdata;
}
add_filter( 'preprocess_comment' , 'overwrite_comment_post_id' );

Since the preprocess_comment filter doesn't yet have a comment ID (comment hasn't been saved), I don't know how I can access my custom field value here?

I have also read about the comment_post action (as suggested here on StackExchange), but I can't figure out how to get my custom field here either.

If anyone has any other suggestions, I would be curious to hear them!

Updated code

function comment_post_id_update( $comment_ID, $comment_approved, $commentdata ) {
    $commentdata = [];
    $commentdata['comment_post_ID'] = $_POST['acf']['field_6278d64aecf19'];
    wp_update_comment($commentdata);
}
add_action( 'comment_post', 'comment_post_id_update', 10, 3 );

Topic advanced-custom-fields comments custom-field Wordpress

Category Web


This bit of code will update the comment_post_ID with the value submitted using your custom form.

function wpse405448_update_comment( $comment_ID, $comment_approved, $commentdata ) {
    if ( isset($_POST['acf']['field_6278d64aecf19']) && !empty($_POST['acf']['field_6278d64aecf19']) ) {
        $comment_post_id = intval($_POST['acf']['field_6278d64aecf19']);
        
        $com_arr = array(
            'comment_ID' => $comment_ID,
            'comment_post_ID' => $comment_post_id,
        );
        
        wp_update_comment($com_arr);
    }
}
add_action( 'comment_post', 'wpse405448_update_comment', 10, 3 );

Make sure both the comment_ID and comment_post_ID are valid. Otherwise it wont get updated.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.