カテゴリー
WordPress

カスタムテンプレートファイルのみ処理を分岐する

WordPress 案件で、特定の「カスタムページテンプレート」を表示している場合のみ処理を変えてほしいという話がありました。

WordPress の関数 is_page_template() で、使用しているテンプレートが判別できるので、これが利用できますね。

(例) custom_news_template.php を使用している際に 追加の CSS ファイルを読み込む。

functions.php で wp_enqueue_scripts フックで、追加CSS を読み込む際に条件分岐させる

function add_custom_css() {
    if ( is_page_template("custom_news_template.php") ){
        wp_enqueue_style( 'custom_news_style', get_template_directory_uri() . '/css/custom_news_style.css', "", '20190409' );
    }
}
add_action( 'wp_enqueue_scripts', 'add_custom_css' );

又は header.php で

<?php if ( is_page_template("custom_news_template.php") ): ?>
    <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/custom_news_style.css">
<?php endif; ?>