Web制作で役立つメモをWEB MEMO LOG

2024.10.09

【WordPress】特定のスラッグやIDの固定ページを複数取得し表示する方法

特定スラッグの固定ページを複数取得し表示する場合

<?php
$slugs = array('slug1', 'slug2', 'slug3');  // 取得したいスラッグのリスト

$args = array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'post_name__in' => $slugs,  // 複数スラッグを指定
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <div><?php the_content(); ?></div>
        <?php
    }
    wp_reset_postdata();
} else {
    echo 'ページが見つかりません。';
}
?>

特定IDの固定ページを複数取得し表示する場合

<?php
// 取得したい固定ページのIDを指定
$page_ids = array(12, 34, 56);  // 固定ページのIDを指定

$args = array(
    'post_type' => 'page',      // 固定ページを指定
    'post_status' => 'publish', // 公開されているページのみ
    'posts_per_page' => -1,     // すべての該当ページを取得
    'post__in' => $page_ids,    // 取得するページのIDを指定
    'orderby' => 'post__in',    // 指定したIDの順に表示するため
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <div><?php the_content(); ?></div>
        <?php
    }
    // 投稿データをリセット
    wp_reset_postdata();
} else {
    echo 'ページが見つかりません。';
}
?>

About Site

同じことを何度も検索していたりするんで、検索して解決したことを残そうと思いまして。