WP_Remote_Get Not working

I have a plugin which uses wp_remote_get() and it's not working on my nginx server so I decided to test this.

I created a file called test.php and inserted:

?php $response = wp_remote_get( 'http://www.domain.com/mytest.php' );

print $response ['body']; ?

When I run this file I am getting error:

2017/02/04 16:22:31 [error] 16573#16573: *461100 FastCGI sent in stderr:
…

 "PHP message: PHP Fatal error:  Uncaught Error: Call to undefined function
 wp_remote_get() in /var/www/html/wp-content/themes/x-child/test.php:1

I cannot tell why this would be undefined function, given that its part of wordpress core?

Topic wp-remote-get functions core Wordpress

Category Web


The very concept of HTTP API is to make sure transport will be done. It basically uses 5 different transport methods and it chooses the best one according to your server config. So it's unlikely a compatibility issue with wp_remote_get() and your server.

Plus if WP is not loaded, adding an action won't help, it will fail the same with undefined function error but this time on add_action.

So basically you're missing WordPress, for test purpose you could do this (assuming your file is at the root of WP installation ) :

<?php 
require_once( 'wp-load.php' );
$response = wp_remote_get( 'http://www.domain.com/mytest.php' );
print $response ['body']; ?>

Are you trying to access your test.php file directly? If so, then WordPress won't be loaded, so wp_remote_get() won't work.

To use wp_remote_get you need to make sure WordPress is loaded. Try hooking into wp_loaded:

add_action( 'wp_loaded', function() {
  $response = wp_remote_get( 'https://example.com/' );
  print $response[ 'body' ];
} );

There's a chance your server is configured in such a way that the methods used by wp_remote_get are not available to WordPress. If that's the case, make sure curl or wget is installed on the server.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.