1

I want to use the comment form I have built to then transfer data directly into an entry within Gravity Forms. I'm thinking it can work from this:

Someone fills out comment form. If checkbox is ticked, I collect the name and email of the commenter and add as an entry to a Gravity Form.

Nobody will ever see an actual Gravity form but want to know how this can be done. I assume this is done by passing parameters to the next URL after the comment is submitted, then caught by a function that then uses this data to store as an entry.

1 Answer 1

3

This is possible using the comment_post action, and the GFAPI class which handles entries in WordPress.

What you need to first is add using comment_form_default_fields a field which is a checkbox.

function add_to_email_list_field($fields) {

    $fields['add-to-email'] = '<p class="comment-form-public">
    <input id="addtoemail" name="addtoemail" type="checkbox" />
    <label for="addtoemail">
    Check this box to add yourself to our email list.
    </label></p>';
    return $fields;
}
add_filter('comment_form_default_fields','add_to_email_list_field');

This adds to the comment form (before the actual comment box) a checkbox. If it's checked, we need to add an entry object to Gravity Forms. This form assumes that the first field is the name, and the second field is email, and the form ID is 1. This will need changing on your site:-

function save_to_gravity_form( $post_id ) {
     $save_meta_checkbox = esc_attr( $_POST['addtoemail'] );

    if ( $save_meta_checkbox == 'on' ) {
        $entry = array( 'form_id' => 1, // Change form ID to your Gravity Form ID
            1 => esc_attr( $_POST['name'] ), // Change 1 to the field ID in your Gravity Form for Name 
            2 => esc_attr( $_POST['email'] // Change 2 to the field ID in your Gravity Form for Email )
        );
        $entry_id = GFAPI::add_entry($entry);

        if ( is_wp_error( $entry_id ) ) {
            wp_die( $entry_id->get_error_message() );
        }
    }

}
add_action( 'comment_post', 'save_to_gravity_form', 1 );

That is very quick, so hopefully that works for you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.