ほぼ社内用の備忘録です。
よく使うコードなので紹介します。
主に「page.php」で使用するコードです。
現在のページが子ページであるとき、その親要素に紐づいている子ページ(=兄弟ページ)をリストで一覧出力する方法です。
<?php
if ($post->post_parent) {
$current_page_id = get_the_ID();
$parent_id = $post->post_parent;
$child_pages = new WP_Query(array(
'post_type' => 'page',
'post_parent' => $parent_id,
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1
));
if ($child_pages->have_posts()) : ?>
<div class="page-selector">
<ul>
<?php while ($child_pages->have_posts()) : $child_pages->the_post(); ?>
<li class="button <?php echo (get_the_ID() === $current_page_id) ? 'is-current' : ''; ?>">
<a href="<?php the_permalink(); ?>">
<?php the_title_attribute(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
</div>
<?php
endif;
wp_reset_postdata();
}
?>
現在のページと同じリンクには「is-current」クラスを付与しています。
ぜひご利用ください。