要透過文章 ID 的陣列來取得對應的文章內容,可以使用 WordPress 提供的 get_post() 函式。以下是如何實現的範例:
function get_posts_by_ids($post_ids) {
$posts = array();
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
if ($post) {
$posts[] = $post;
}
}
return $posts;
}
// 假設您有一個文章 ID 的陣列
$post_ids = array(123, 456, 789);
// 取得對應的文章內容
$posts = get_posts_by_ids($post_ids);
// 顯示文章內容
foreach ($posts as $post) {
echo $post->post_title;
}
這個 get_posts_by_ids 函式接受一個文章 ID 的陣列 $post_ids,並返回包含對應文章內容的陣列。
在函數中掃過 $post_ids 陣列並使用 get_post() 函數取得每個文章的內容。如果文章存在(未被刪除),則將其加入到 $posts 陣列中。
經由 $posts 陣列顯示每個文章的標題和內容,這樣就可以透過文章 ID 的陣列來取得對應的文章內容。