9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[wordpress] 固定ページ化したときにcssが崩れちゃう問題

Posted at

page-xxx.php ページに直接 HTML を書いていたときは崩れなかったレイアウトが、管理画面からhtmlを編集できるようにテンプレート側を the_content(); に切り替えて 管理画面から固定ページで HTML を貼り付けた途端にガタガタになっちゃった!……。
DevTools を開き確認すると勝手に <p> タグや改行が挿入されているのが原因でした。この記事ではその時の解決をメモします。

1. 再現した手順

  1. page-happy.php を作り、ヘッダー・フッターを呼び出しつつ中身は直書き:

    <?php /* Template Name: LP (Hard‑coded) */ ?>
    <?php get_header(); ?>
    <section class="kv"><h1>Title</h1></section>
    <section class="features"></section>
    <?php get_footer(); ?>
    

    表示 OK

  2. 本文を投稿画面から編集できるようにする。

    <?php /* Template Name: LP (Editor) */ ?>
    <?php get_header(); ?>
    <?php the_content(); ?>
    <?php get_footer(); ?>
    
  3. 固定ページ編集画面に、さきほどの HTML 全文をコピペ → 更新。

  4. 表示を確認すると CSS が崩壊。DevTools でみると:

    <p><section class="kv"><h1>Title</h1></section></p>
    <p><section class="features"></section></p>
    

    <p> ラップ + <br> 挿入でセレクタが想定外に。


2. 原因 – wpautop フィルタ

WordPress は投稿本文 (the_content) を表示する直前に wpautop() を走らせ、改行を自動で <p> / <br /> に変換します。

  • ブログ記事には便利だが、HTML をそのまま貼りたい LP には邪魔
  • <section> などブロックレベル要素を <p> で包むため、CSS のセレクタ階層が変わり崩れる。

3. 解決策

3‑2. テンプレート側で wpautop を無効化(最短)

<?php /* Template Name: LP (No‑autop) */ ?>
<?php
  /* p タグ自動挿入を殺す */
  remove_filter( 'the_content', 'wpautop' );
  remove_filter( 'the_content', 'shortcode_unautop' );
?>
<?php get_header(); ?>
<?php the_content(); ?>
<?php get_footer(); ?>

ポイント : 同じテンプレート内で remove_filter()the_content() の順に呼ぶ。ほかのページへの影響はない。

まとめ

Before After 効果
the_content() + wpautop()<p> 挿入 remove_filter( 'the_content', 'wpautop' ) 余計なラップを防ぎ、CSS が元どおり

教訓 : LP や静的ページを投稿エディタで管理するときは、まず wpautop を疑う!
もうひとこと : WordPress のエディタは “ページをその場で組み立てる” には便利ですが、外部ツールで作成したデザインをそのままコピペすると自動整形で <p> など余計なタグが入り、レイアウトが崩れやすい。コピー&ペースト運用をする場合は、3-0 / 3-1 の対策を必ず入れるようにする!

9
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?