phpjsonwordpresswordpress-rest-apiwp-api

WordPress: Get posts from other site with BasicAuth protection via Rest API


I want to get post from a site with BasicAuth protection.

To get the post from the site I'm using the following code (from here):

// Disable direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Get posts via REST API.
 */
function get_posts_via_rest() {

    // Initialize variable.
    $allposts = '';
    
    // Enter the name of your blog here followed by /wp-json/wp/v2/posts and add filters like this one that limits the result to 2 posts.
    $response = wp_remote_get( 'https://www.sumydesigns.com/wp-json/wp/v2/posts?per_page=2' );

    // Exit if error.
    if ( is_wp_error( $response ) ) {
        return;
    }

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

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

    // If there are posts.
    if ( ! empty( $posts ) ) {

        // For each post.
        foreach ( $posts as $post ) {

            // Use print_r($post); to get the details of the post and all available fields
            // Format the date.
            $fordate = date( 'n/j/Y', strtotime( $post->modified ) );

            // Show a linked title and post date.
            $allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a>  ' . esc_html( $fordate ) . '<br />';
        }
        
        return $allposts;
    }

}

It works. But the site I want to get the post from uses a BasicAuth protection. So there is no result.

I read that the Rest API couldn't handle BasicAuth. And I have to use a plugin like the Basic Authentication handler

But I'm not sure how to use it. Is there a way to integrate it in the code?


Solution

  • Within WordPress WP_Http are made through the wp_remote_get() function.

    Performs an HTTP request using the GET method and returns its response.

    In short wp_remote_get() act as a wrapper for WP_Http.

    Performs an HTTP request using the GET method and returns its response.

    As per BasicAuth documentation:

    <?php
    
    $args = array(
        'headers' => array(
            //here the credentials are referring to a wordpress account on the targeted website
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
        ),
    );
    
    wp_remote_get('https://...com/wp-json/wp/v2/posts', $args);
    //...
    

    You can definitely prevent api access (but that's not natively the case).

    Keep in mind that, using BasicAuth will probably not be useful. When people go for the hassle that is securing the api, usually it requires an admin access level to access the api.

    An alternative would be to use a scraper like puppeteer to re-create a api from scratch and host it on a separate server. (sounds complicated but it's pretty easy)