要在WordPress站外調用某個分類下的6個隨機文章,你可以使用WordPress REST API。以下是一個示例代碼,展示了如何使用JavaScript和jQuery來實現這個功能:
1. 首先,確保你的WordPress站點已經啟用了REST API。在`functions.php`文件中添加以下代碼:
add_action('rest_api_init', function () {
register_rest_route('your-plugin/v1', '/random-posts/(?P<category_id>\d+)/(?P<count>\d+)', array(
'methods' => 'GET',
'callback' => 'get_random_posts',
));
});
function get_random_posts($request) {
$category_id = $request['category_id'];
$count = $request['count'];
$args = array(
'category' => $category_id,
'orderby' => 'rand',
'posts_per_page' => $count,
);
$query = new WP_Query($args);
$posts = $query->get_posts();
$data = array();
foreach ($posts as $post) {
$data[] = array(
'title' => $post->post_title,
'link' => get_permalink($post->ID),
);
}
return rest_ensure_response($data);
}
這段代碼會創建一個新的REST API路由,允許你通過`/wp-json/your-plugin/v1/random-posts//`來獲取隨機文章。
2. 在你的前端頁面中,使用以下JavaScript代碼來調用API并顯示結果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Posts</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="random-posts"></div>
<script>
$(document).ready(function() {
var categoryId = 1; // 替換為你想要的分類ID
var count = 6;
$.ajax({
url: 'https://wodepress.com/wp-json/your-plugin/v1/random-posts/' + categoryId + '/' + count,
type: 'GET',
success: function(data) {
var randomPostsHtml = '<ul>';
$.each(data, function(index, post) {
randomPostsHtml += '<li><a href="' + post.link + '">' + post.title + '</a></li>';
});
randomPostsHtml += '</ul>';
$('#random-posts').html(randomPostsHtml);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: ' + textStatus + ' - ' + errorThrown);
}
});
});
</script>
</body>
</html>
請確保將`categoryId`變量替換為你想要的分類ID,并將`wodepress.com`替換為你的WordPress站點URL。這段代碼會在頁面加載完成后,通過AJAX調用你創建的REST API路由,并將結果顯示在頁面上。
請注意,這段代碼需要在支持JavaScript和jQuery的環境中運行,并且你的WordPress站點需要允許跨域請求,如果前端頁面不在同一個域名下。