wordpress WordPressの親子関係のある固定ページで子ページ一覧表示の際のカラム落ち防止 作成日: 2025年7月27日
あまり使わないけど、数が少ないが増減あるページ一覧表示で、スマホなら1カラムだがPCなら3カラムの場合3で割り切れないとカラム落ちする。
普通にアーカイブ/カテゴリーなら表示数も想定上多いし、ページネーションあるから気にしないところだが、構成によっては起こり得るもの。
子ページの数により親要素に属性付けて処理する形(の方が汎用性高い)で組んでみた。
<?php //子ページ数の増減ありでカラム落ちさせず収める場合の3カラム仕様
$parent_id = get_the_ID();
$args = array(
'post_type' => 'page',
'post_parent' => $parent_id,
'posts_per_page' => -1, // 全ての子ページを取得
'post_status' => 'publish',
'orderby' => 'menu_order', // メニュー順で並び替え(必要であれば)
'order' => 'ASC',
);
$child_pages_query = new WP_Query($args);
// 子ページの総数を取得
$total_child_pages = $child_pages_query->post_count;
$container_extra_class = ''; // 親要素に追加するクラスを格納する変数
if ($total_child_pages > 0) { // 子ページがある場合のみ計算
$remainder = $total_child_pages % 3; // 3で割った余りを計算
if ($remainder === 1) {
$container_extra_class = 'single'; // 1カラム落ちの場合に 'single' クラスを付与
} elseif ($remainder === 2) {
$container_extra_class = 'twice'; // 2カラム落ちの場合に 'twice' クラスを付与
}
}
?>
<?php if ($child_pages_query->have_posts()) :?>
<section class="<?php echo esc_attr($container_extra_class); ?>">
<?php while ($child_pages_query->have_posts()) : $child_pages_query->the_post();?>
<div>
<a href="<?php the_permalink(); ?>">
<picture><img src="<?php if (has_post_thumbnail()): ?><?php the_post_thumbnail_url('thumbnail'); ?><?php else: ?><?php $post_content = apply_filters('the_content', get_the_content()); ?><?php $first_img_url = ''; ?><?php preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post_content, $matches); ?><?php if (!empty($matches[1])): ?><?php echo esc_url($matches[1]); ?><?php else: ?><?php echo esc_url( home_url( '/' ) ); ?><?php echo get_option('site_defaultimg'); ?><?php endif; ?><?php endif; ?>" alt="<?php the_title(); ?>">
</picture>
<h3><?php the_title(); ?></h3>
</a>
</div>
<?php endwhile;?>
<?php wp_reset_postdata();?>
</section>
<?php endif;?>
カラム落ちが1ならsingle、2ならtwiceってクラスが付く
singleの時はfirst-of-typeでwidth100%、twiceの時はnth-of-typ(-n + 2)でwidth50%指定にすると、(新しい順に)コマが大きく表示される構成になる。