WordPress:通过 Rest 从具有 BasicAuth 保护的其他站点获取帖子 API

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

我想从具有 BasicAuth 保护的站点获取 post。

要从网站获取 post,我使用以下代码 (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;
    }

}

有效。 但是我想从中获取 post 的站点使用了 BasicAuth 保护。 所以没有结果。

我读到 Rest API 无法处理 BasicAuth。 而且我必须使用像 Basic Authentication handler

这样的插件

但我不确定如何使用它。 有没有办法将它集成到代码中?

在 WordPress 中 WP_Http 是通过 wp_remote_get() 函数创建的。

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

简而言之 wp_remote_get() 充当 WP_Http 的包装器。

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

根据 BasicAuth 文档:

<?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);
//...

您绝对可以阻止 api 访问(但本地情况并非如此)。

请记住,使用 BasicAuth 可能没有用。当人们为保护 api 的麻烦而烦恼时,通常需要管理员访问级别才能访问 api。

另一种方法是使用像 puppeteer 这样的抓取工具从头开始重新创建 api 并将其托管在单独的服务器上。 (听起来很复杂,其实很简单)