Contact form 7: How can I run PHP code after submitting? Is it possible?
I have PHP curl code. I want to run it, but how can I do it?
My PHP code:
<?php
$data = array(
'chatId' => '[email protected]',
'mentions' => array(
'[email protected]'
),
'text' => 'Hi there!',
'session' => 'default'
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n",
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('http://1.1.1.1:3000/api/sendText', false, $context);
echo $result;
?>
Is it possible? How can I do it?
Yes, it is possible to execute custom PHP code after a form submission with Contact Form 7 in WordPress. However, to integrate custom PHP code like yours, you need to hook into Contact Form 7's wpcf7_before_send_mail action. This action allows you to run custom code before the email is sent, which is essentially right after the form submission.
Here's how you can do it:
Add the following code to your theme's functions.php file or a custom plugin. This code hooks into the wpcf7_before_send_mail action and executes your custom PHP code.
Replace 'Your Form Name' with the actual name of your Contact Form 7 form. This is to ensure the custom code runs only for the specified form. If you want your code to run for every form submission, you can remove the if condition that checks the form title.
Ensure that your server is configured to allow outgoing HTTP requests via file_get_contents and that it supports the PHP stream context options you're using. Some hosting environments disable file_get_contents for URLs or restrict its usage due to security reasons. In such cases, you might need to use cURL or a WordPress-specific HTTP API like wp_remote_post.
Be cautious with security. Make sure your target URL ('http://1.1.1.1:3000/api/sendText') is secure and trusted. Sending data to external servers can introduce security risks.
After adding this code, test your form submission to ensure that your custom PHP code executes as expected and the external API call is made successfully.