html获取WordPress文章
时间 : 2024-01-03 10:28:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

要获取WordPress文章的HTML,您可以使用WordPress提供的REST API来获取文章的内容和元数据。以下是一个使用JavaScript来获取WordPress文章的例子:

```javascript

// 使用fetch函数获取文章内容

fetch('https://example.com/wp-json/wp/v2/posts/{post_id}')

.then(response => response.json())

.then(data => {

// 获取文章内容

const content = data.content.rendered;

// 将内容插入到HTML元素中

document.getElementById('post-content').innerHTML = content;

// 获取文章标题

const title = data.title.rendered;

// 将标题插入到HTML元素中

document.getElementById('post-title').innerText = title;

// 获取作者信息

const authorId = data.author;

fetch('https://example.com/wp-json/wp/v2/users/' + authorId)

.then(response => response.json())

.then(userData => {

// 获取作者姓名

const authorName = userData.name;

// 将作者信息插入到HTML元素中

document.getElementById('author-name').innerText = authorName;

});

});

在上面的示例中,您需要将`https://example.com`和`{post_id}`替换为您的WordPress网站的URL和要获取的文章的ID。您可以使用这个例子来获取文章的标题、内容和作者信息,并将它们插入到HTML元素中。

其他答案

要在HTML中获取WordPress文章,您可以使用WordPress的REST API。下面是一个示例代码,可以使用JavaScript获取文章并动态显示在HTML页面中:

```javascript

<!DOCTYPE html>

<html>

<head>

<title>获取WordPress文章</title>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</head>

<body>

<div id="post-container"></div>

<script>

$(document).ready(function() {

$.ajax({

url: 'https://your-wordpress-site/wp-json/wp/v2/posts', // 替换为您的WordPress网站URL

dataType: 'json',

success: function(data) {

var postContainer = $('#post-container');

if (data && data.length > 0) {

$.each(data, function(index, post) {

var postTitle = $('<h2/>').text(post.title.rendered);

var postContent = $('<div/>').html(post.content.rendered);

postContainer.append(postTitle);

postContainer.append(postContent);

postContainer.append('<hr>');

});

} else {

postContainer.text('没有找到文章');

}

},

error: function() {

$('#post-container').text('无法获取文章');

}

});

});

</script>

</body>

</html>

请确保将`https://your-wordpress-site/wp-json/wp/v2/posts`替换为您的WordPress网站的正确URL。此代码将使用jQuery在DIV容器中动态显示所有文章的标题和内容。如果无法检索到文章,将显示相应的错误消息。