🔰はじめての方へ

【WordPress】オリジナルのページを作成/画像パスの書き方・CSSを引き継がない方法

記事内に広告が含まれています。
スポンサーリンク

WordPressで採用ページのオリジナルページを作成しています!

作成方法や、困ったことの対処法などは別の記事に書いてありますので、ご参照ください!

作成方法について
ページの表示確認ができないトラブル

今回は、①画像のパスの書き方 と ②親CSSを読み込まない方法についてお話します!

①画像のパスの書き方

子テーマの images フォルダに画像を置く(新たに作成)

(例:/wp-content/themes/child-theme/images/hero.jpg

CSS(相対パス(images/hero.jpg)で書くのがベター)

.hero {
  background: url("images/bg.png") no-repeat center center;
}

HTML(子テーマディレクトリのURLを取得する関数を使う)

<a href="/" class="logo-link">
    <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png" alt="ロゴ">
</a>

②親CSSを読み込まない方法

下記のように、functions.php に記載していきます。

<?php
// 親・子テーマのCSSを読み込む処理
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style') );
}

// 採用LP専用のCSSとJSを読み込み、テーマCSSを外す
function enqueue_recruit_lp_assets() {
    if ( is_page_template('page-recruit.php') ) {
        // 親・子テーマのCSSを読み込まないようにする
        wp_dequeue_style('parent-style');
        wp_dequeue_style('child-style');
        wp_deregister_style('parent-style');
        wp_deregister_style('child-style');

        // 採用LP専用CSS
        wp_enqueue_style(
            'recruit-lp',
            get_stylesheet_directory_uri() . '/page-recruit.css',
            array(),
            time()
        );

        // 採用LP専用JS
        wp_enqueue_script(
            'recruit-lp',
            get_stylesheet_directory_uri() . '/recruit-lp.js',
            array(),
            time(),
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'enqueue_recruit_lp_assets', 20);
  • is_page_template('page-recruit.php') → 採用LPだけ判定。
  • wp_dequeue_style() → 読み込みキューから外す。
  • wp_deregister_style() → 登録そのものを解除。
  • add_action(..., 20) → 最初に親子テーマCSSを読み込んでから、後でキャンセルするため優先度20を指定。