【发布时间】:2022-01-21 13:27:36
【问题描述】:
我想从一个有 BasicAuth 保护的网站上发帖。
要从网站获取帖子,我使用以下代码 (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;
}
}
它有效。 但是我想从中获取帖子的网站使用 BasicAuth 保护。 所以没有结果。
我了解到 Rest API 无法处理 BasicAuth。 而且我必须使用像Basic Authentication handler这样的插件
但我不确定如何使用它。 有没有办法把它集成到代码中?
【问题讨论】:
标签: php json wordpress wordpress-rest-api wp-api