Skip to content
Advertisement

How to call a PHP cURL function in a WordPress website

I have a need to call the REST API with GET request in my wordpress website. The requirement is whenever we search any product from the search form, the PHP curl function should give the response. The PHP function I have already implemented as below:

<?php
function callAPI($data)

{

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://price-api.datayuge.com/api/v1/compare/search? 
    api_key=API_KEY&product=" . $data . "&page=1",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "content-type: application/json"
    ) ,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err)
{
    echo "cURL Error #:" . $err;
}
else
{
    return $response;
}
}

?>

I’m new to PHP and all this web development. I’m doing this stuff because I am curious to learn by practice. So kindly help me in implementing this function call in wordpress website search form. I’m also not aware how the search form will send the $data parameter (which will contain user input) to the function while calling. So please tell the approach including this parameter also. And also please tell from where this function should be called in wordpress?

My new implementation:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- 
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<p>Search any product</p>
<input id="userInput" type="text" placeholder="Search...">
<button onclick="returnText()">Submit</button>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function returnText() {
    let input = document.getElementById("userInput").value;
    alert(input)
    $.ajax({
        url: 'https://wattaprice.com/price-compare/', //This is 
     the current doc
        type: "GET",
        data: (input),
        success: function(data) {
            console.log(data);
            alert(data);
            //or if the data is JSON
        }
    });
}
</script>
</body>

</html>




<?php
if (isset($_GET['input']))
{

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://price- 
api.datayuge.com/api/v1/compare/search? 
api_key=API_KEY&product=" . $input . 
"&page=1",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "content-type: application/json"
    ) ,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err)
{
    echo "cURL Error #:" . $err;
}
else
{
    $final_result = json_decode($response, true);
    var_dump($final_result);
}
}
?>

Advertisement

Answer

You can write a JavaScript onclick event to get the value of the search field when the ‘search’ button is clicked. And then send the data (value of input field) via AJAX to the BE and based on that execute your curl request.

In the BE you can write a function and hook it to wp_ajax_${action} or wp_ajax_nopriv_${action} that will handle this request and at the end – send data with wp_send_json.

That would be the cleanest way to do this. Also, you should create some type of indication in the FE that the request is being executed and the user is waiting for a response. I would suggest a spinner loader (this is not mandatory but it enhances the UX).

EDIT: What you’ve missed? – It’s good that your JS is being executed but you never register your function as a wp_ajax request.

How to fix it? – First thing to do is to wrap your CURL request with a function e.g. named get_product_price(). And your code would look like this:

// This function initializes the URL where all AJAX requests in WP are made
function myplugin_ajaxurl() {
   echo '<script type="text/javascript">
         const ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action( 'wp_head', 'myplugin_ajaxurl' );


function get_product_price() {
    ...your curl code here....
}
add_action( 'wp_ajax_nopriv_get_product_price', 'get_product_price' ); // This lets WP know you want to call this function via AJAX.

And then when you call the AJAX this is what you have to do:

$.ajax({
    url: ajaxurl,
    type: "GET",
    data: (input),

… continue code as it was ….

This way you make an AJAX request to your BE which will use curl to fetch data from another API.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement