2017-04-24 68 views
-1

我嘗試從外部WordPress頁面(即帖子)提取某個部分,然後將其嵌入到一個簡單的站點中。JQuery提取WordPress帖子

我試過​​,但它似乎沒有工作,我真的不知道如何繼續。

+0

你能分享一些代碼,你有什麼迄今所做? – NewUser

+0

通過_extract某個part_你指的是[廢棄網站]的能力(https://en.wikipedia.org/wiki/Web_scraping)。或者你想顯示整個外部WP頁面到您的網站。真的很感謝代碼和問題的詳細解釋。 –

回答

0

WordPress的提供REST API訪問其帖子,評論,網頁等。對於帖子你可以看看https://developer.wordpress.org/rest-api/reference/posts/#list-posts條目。

所以,你可以用下面的代碼來提取帖子列表:

$.ajax({ 
    method: "GET", 
    url: "http://your.website/wp-json/wp/v2/posts/", 
    dataType: "json", 
}) 
.done(function(response){console.log(response);}) 
.fail(function(xhr, status){console.log(status);}); 

記住,你需要有允許此類操作的CORS。瞭解如何在Wordpress中啓用CORS https://joshpress.net/access-control-headers-for-the-wordpress-rest-api/

如果不是您的網站,請閱讀CORS如何影響您的AJAX請求以及您可以在https://stackoverflow.com/a/17299796/2678487上使用它做什麼。

例如,你可以使用像旁邊,在我的網站訪問WordPress的REST API:

$.ajax({ 
 
    method: "GET", 
 
    url: "http://cors-anywhere.herokuapp.com/blog.binaryspaceship.com/wp-json/wp/v2/posts/", 
 
    dataType: "json", 
 
}) 
 
.done(function(response){ 
 
    $('#result').html(
 
    JSON.stringify(response, null, 2) 
 
); 
 
}) 
 
.fail(function(xhr, status){alert(status);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 

 
<pre id="result"></pre>

+0

非常感謝,我會免費試用! –

+0

@ConstiP,歡迎您:)。 – metamaker