Contact Form 7 is a popular WordPress contact form plugin that allows you to easily create a contact form on your website.
WPGetAPI can interact with Contact Form 7 to gather the data that is submitted through a form, and then use this data as a variable to send to any external API.
We will outline the steps that will allow you to integrate Contact Form 7 with WPGetAPI. In our example we are just using a quick test example to connect to the Binance API and retrieve the price of a cryptocurrency pair. Other more suitable uses for this could be something like sending a subscriber email address to your email marketing platform.
Setup Contact Form 7
Once you have Contact Form 7 installed, you will need to add a form. Visit the Contact Form 7 docs for help in setting this up – https://contactform7.com/getting-started-with-contact-form-7/
We have set up our form with the following fields:
- your-name
- your-email
- the-value – this is what we will use to send to our API
In the Additional Settings tab we have also added “skip_mail: on” which stops the email being sent (which is default for Contact Form 7 as it is a contact form).
Now we just need to add the shortcode [contact-form-7 id=”7959″ title=”Untitled”] to our page and it will display our form.
Setup the Binance API
The settings for our Binance API are shown in the screenshot below and you can see that we are using the endpoint: https://api.binance.com/api/v3/avgPrice
Process the form and get the API data
We now need to add the following code into our themes functions.php file. This will basically get our form value, which will be a cryptocurrency pair and then send this as a query variable to the Binance API to retrieve the price. We are then modifying the output of the forms message to give us the price.
// hook into the contact form 7 action upon processing the form
add_action( 'wpcf7_before_send_mail', 'wpgetapi_send_data_to_api', 10, 3 );
function wpgetapi_send_data_to_api( $contact_form, &$abort, $submission ) {
// Getting user input through the the-value field
$the_value = $submission->get_posted_data( 'the-value' );
// call the binance api and retrieve the 'price' key
$price = wpgetapi_endpoint( 'binance', 'price_of_coin',
array(
'debug' => false,
'query_variables' => 'symbol=' . $the_value,
),
array(
'price'
)
);
// get the form properties
$properties = $contact_form->get_properties();
// set the success message
$properties['messages']['mail_sent_ok'] = 'Current '. $the_value . ' price is ' . $price;
$contact_form->set_properties($properties);
}
View the results
Now it is just a matter of testing our form to see the results, which will be the current live price of a cryptocurrency pair from Binance.