简体   繁体   English

将 WP/WooCommerce 用户与 CF7 表单关联

[英]Associate WP/WooCommerce user with CF7 form

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?如果在 WP 的“会员区”中使用 CF7 表单,如果用户最初是通过 WooCommerce 购买创建的,是否有办法关联谁提交表单?

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.我知道我们可以将他们的用户名作为表单的一部分来询问,但我正在寻找一种更好的方法来解决这个问题,即表单自动提取用户 ID。 We will then push the form submission through a webhook and add automation on the backend based on the form response.然后我们将通过 webhook 推送表单提交,并根据表单响应在后端添加自动化。 It's just this first part I'm looking for help with, and I have not found any good articles on it.这只是我正在寻求帮助的第一部分,我还没有找到任何关于它的好文章。

WordPress allows you to query who is currently logged in user for a given requests/form submission with the function get_current_user_id() . WordPress 允许您使用函数get_current_user_id()查询当前登录用户的给定请求/表单提交。 However, logged-in user credentials are not preserved during a REST api/AJAX call.但是,在 REST api/AJAX 调用期间不会保留登录的用户凭据。 CF7 uses the REST api to submit forms and therefore it is not possible to use this function for a CF7 form submission. CF7 使用 REST api 提交表单,因此无法将此函数用于 CF7 表单提交。

You have 2 ways to solve this problem,你有两种方法可以解决这个问题,

.1. .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,使用Smart Grid-layout 扩展,它修复了 CF7 插件的许多编码问题,其中之一是在表单提交时保留用户凭据,因此允许您使用上述功能,

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. .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.或者,您需要将当前用户的 ID 作为隐藏字段添加到表单中,以便在提交表单后检索它。 See this answer for an example.有关示例,请参阅此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM