我想從具有 BasicAuth 保護的站點獲取帖子。
要從網站獲取帖子,我使用以下代碼(來自此處):
// 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 處理程式這樣的插件
但我不確定如何使用它。有沒有辦法將它集成到代碼中?
uj5u.com熱心網友回復:
WordPress 內WP_Http都是通過該wp_remote_get()功能進行制作的。
使用 GET 方法執行 HTTP 請求并回傳其回應。
簡而言之,wp_remote_get()充當WP_Http.
使用 GET 方法執行 HTTP 請求并回傳其回應。
根據 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 并將其托管在單獨的服務器上。(聽起來很復雜,其實很簡單)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/387253.html
標籤:php json WordPress的 wordpress-rest-api wp-api
上一篇:如何展平一組物件?[復制]
