WPForms is a popular WordPress contact form plugin that allows you to easily create any type of form on your website.
WPGetAPI can interact with WPForms 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 WPForms 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 WPForms
Once you have WPForms installed, you will need to add a form. Visit the WPForms docs for help in setting this up – https://wpforms.com/docs/
We have simply set up our form with the following field:
- Crypto Pairs – this is what we will use to send to our API (note the ID of the field is #1 as this will be used in our code)
Now we just need to add the shortcode [wpforms id=”7961″] 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.
function wpf_dev_process_filter( $message, $form_data, $fields, $entry_id ) {
// Only run on my form with ID = 7961
if ( absint( $form_data['id'] ) !== 7961 ) {
return $message;
}
// Get the crypto pair symbol from the form
$symbol = $fields['1']['value'];
// call the binance api and retrieve the 'price' key
$price = wpgetapi_endpoint( 'binance', 'price_of_coin',
array(
'debug' => false,
'query_variables' => 'symbol=' . $symbol,
),
array(
'price'
)
);
// output our message to the user
$message = 'Current '. $symbol . ' price is ' . $price;
return $message;
}
add_filter( 'wpforms_frontend_confirmation_message', 'wpf_dev_process_filter', 10, 4 );
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.