我也有同样的需求,后来我找到了一种方法。
使用 WPForms 实际上非常简单。
WPForms 具有hooks,因此您可以使用wpforms_process_complete 挂钩轻松跟踪表单提交。这个钩子允许你跟踪 ALL WPForms sumbission。但也许你想要不同的形式。如果您只想跟踪特定表单,可以将表单 id 添加到挂钩名称的末尾。
在我的情况下,我有许多不同的表格,它们以不同的方式处理,所以我不得不将它们分开。在 WPForms 中创建 表单 时,它会收到一个 ID,命名表单的 字段 也会收到。
在我的表单创建后,它具有以下 id:
钩子函数。
正如Discord Webhook page 中所述,Webhooks 是一种将消息发布到 Discord 中的频道的简单方法。它们不需要机器人用户或身份验证即可使用。端点支持 JSON 和表单数据体。就我而言,我选择了 JSON。
正如here 解释的那样,您只需要使用content file 或embeds 字段之一。在此示例中,我将只发送一条消息,因此我将使用 content 字段。
一旦应用了上述说明,您最终应该会得到接近以下功能的东西:
if ( ! function_exists( 'discord_form_submission' ) ) :
/**
* This will fire at the very end of a (successful) form entry.
*
* @link https://wpforms.com/developers/wpforms_process_complete/
*
* @param array $fields Sanitized entry field values/properties.
* @param array $entry Original $_POST global.
* @param array $form_data Form data and settings.
* @param int $entry_id Entry ID. Will return 0 if entry storage is disabled or using WPForms Lite.
*/
function discord_form_submission( $fields, $entry, $form_data, $entry_id )
{
// You have to replace this url by your discord webhook.
$endpoint = 'https://discord.com/api/webhooks/{webhook.id}/{webhook.token}';
// This is the content you can put anything you wish.
// In my case i needed the Name, Class, and the Level of the players.
$content = "**Name :** " . $fields[1]['value'] . PHP_EOL;
$content .= "**Class :** " . $fields[2]['value'] . PHP_EOL;
$content .= "**Level :** " . $fields[3]['value'] . PHP_EOL;
// WP has its own tool to send remote POST request, better use it.
wp_remote_post( $endpoint , [
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'body' => wp_json_encode([ // Same for the JSON encode.
'content' => $content,
]),
'method' => 'POST',
'data_format' => 'body'
]);
}
endif;
此功能必须添加到您的主题的functions.php文件中。
最后但同样重要的是,在 WP add_action 函数的帮助下,您需要与 wpforms_process_complete 挂钩。在我的情况下,因为我只想用 id 1862 连接到表单,所以我在钩子的末尾添加了 id,它为我们提供了以下代码:
add_action( 'wpforms_process_complete_1862', 'discord_form_submission', 10, 4 );
此代码必须在我们新添加的功能之后添加到您主题的functions.php文件中。