Problem getting wp posts in plugin with wp_remote_get

I am creating a plugin to send posts to an external program. But I get a problem by getting the posts.

I created the code below to get the posts and echo them. But if I run it, it goes to the empty error message. When I echo the response. It only gets 'Array'

If I just post http://localhost/wordpress/wp-json/wp/v2/posts in a browser, I get a JSON with my posts

What am I doing wrong?

$remoteargs = array(
        'timeout'     = 20,
        'redirection' = 5,
        'httpversion' = '1.1',
        'blocking'    = false,
        'headers'     = array(),
        'cookies'     = array(),
        'sslverify'   = false,
    ); 

$response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts', $remoteargs );
// Exit if error.
if ( is_wp_error( $response ) ) {
        echo $response-get_error_message();
            return;
    }
// Get the body.
$posts = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $posts ) ) {
        echo 'emptyerror';
        return;
    }
foreach ( $posts as $post ) {
        echo $post;
}**

Topic wp-remote-get Wordpress

Category Web


Remove or change

 'blocking' => false,

to true as you are not making any Ajax call


I did some changes on my code

        $remoteargs = array(
            'timeout' => 20,
            'redirection' => 5,
            'httpversion' => '1.1',
            'blocking' => false,
            'headers' => array(),
            'cookies' => array(),
            'body' => array(),
            'sslverify' => false,
        );

        $response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts',$remoteargs);

        // Exit if error.
        if ( is_wp_error( $response ) ) {
            echo $response->get_error_message();
            return;
        }

        // Get the body.
        $posts = json_decode( wp_remote_retrieve_body( $response ) );

        // Exit if nothing is returned.
        if ( empty( $posts ) ) {
            var_dump($response);
            return;
        }

It delivers me an empty array like this

array(5) { ["headers"]=> array(0) { } ["body"]=> string(0) "" ["response"]=> array(2) { ["code"]=> bool(false) ["message"]=> bool(false) } ["cookies"]=> array(0) { } ["http_response"]=> NULL }

If I try http://localhost/wordpress/wp-json/wp/v2/posts in a browser of Postmen, it I get the posts. So what is missing in my code?

About

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