0

If using a CF7 form in a "members area" of WP, is there a way to associate who submits the form if the user was originally created through a WooCommmerce purchase?

I know we could just ask for their user name as part of the form, but I'm looking for a better way to solve this where the form automatically pulls in the user ID. We will then push the form submission through a webhook and add automation on the backend based on the form response. It's just this first part I'm looking for help with, and I have not found any good articles on it.

  • 1
    Accepted answer here https://stackoverflow.com/questions/38874189/checking-if-customer-has-already-bought-something-in-woocommerce gives an example code on how to check if user has bought or not. You can use this at the CF7 hook `wpcf7_submit ` to get the desired result – Ozgur Sar Nov 19 '20 at 19:04

1 Answers1

0

WordPress allows you to query who is currently logged in user for a given requests/form submission with the function get_current_user_id(). However, logged-in user credentials are not preserved during a REST api/AJAX call. CF7 uses the REST api to submit forms and therefore it is not possible to use this function for a CF7 form submission.

You have 2 ways to solve this problem,

.1. Use the Smart Grid-layout extension which fixes many coding issues of the CF7 plugin, one of which is the preservation of user credentials on form submissions, therefore allowing you to use the above mentioned function,

add_action('wpcf7_before_send_mail', 'get_cf7_user');
function get_cf7_user($form){
  $user_id = get_current_user_id();
  switch($user_id){
    case 0: //no user logged in.
      break;
    default: //registered user ID.
      $user = wp_get_current_user(); //this is another fn which will get you the user object.
      break;
  }
}

.2. alternatively you will need to add the current user's ID into the form as a hidden field to retrieve it once the form is submitted. See this answer for an example.

Aurovrata
  • 2,000
  • 27
  • 45