Home » Php » php – How do you use curl within wordpress plugins?

php – How do you use curl within wordpress plugins?

Posted by: admin July 12, 2020 Leave a comment


I’m creating a wordpress plugin and I’m having trouble getting a cURL call to function correctly.

Lets say I have a page www.domain.com/wp-admin/admin.php?page=orders

Within the orders page I have a function that looks to see if a button was clicked and if so it needs to do a cURL call to the same page (www.domain.com/wp-admin/admin.php?page=orders&dosomething=true) to kick off a different function. The reason I’m doing it this way is so I can have this cURL call be async.

I’m not getting any errors, but I’m also not getting any response back. If I change my url to google.com or example.com I will get a response. Is there an authentication issue or something of that nature possibly?

My code looks something like this.. I’m using gets, echos, and not doing async just for the ease of testing.


if($_GET['dosomething'] == "true")
     echo("do something");

function curlRequest($url) {
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
How to&Answers:

You’re not supposed to use CURL in WordPress Plugins.

Instead use the wp_ function for issuing HTTP requests, e.g.

function wp_plugin_event_handler () {
    $url = 'http://your-end-point';  
    $foo = 'bar';
    $post_data = array(
         'email' => urlencode($foo));

    $result = wp_remote_post( $url, array( 'body' => $post_data ) );

add_action("wp_plugin_event", "wp_plugin_event_handler");

In the past I’ve run into issues where WordPress plugins event handlers would hang with CURL. Using the WP_ functions instead worked as expected.


The admin section of the blog is password-protected, of course. You’ll need to pass authentication data. Look up http authentication for details. Look specifically here:


You’ll want to set the CURLOPT_USERPWD option and possibly CURLOPT_HTTPAUTH.