LoginSignup
0

More than 3 years have passed since last update.

functions.phpからスタイルシートやjsを読み込む

Posted at

functions.phpからスタイルシートやjsを読み込む

WordPressのwp_head( )とwp_footer( )という関数を読み込んでいく。

そのためには以下をする必要がある。

wp_enqueue_style( )はwp_head()で読み込むcssを追加するための関数で、
wp_enqueue_script( )はwp_footer( )で読み込むjsを追加するための関数です。

下記の内容をfunction.phpに記述。

/**
* CSSとJavaScriptの読み込み
*
* @codex https://wpdocs.osdn.jp/%E3%83%8A%E3%83%93%E3%82%B2%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%83%A1%E3%83%8B%E3%83%A5%E3%83%BC
*/
function my_script_init()
{
wp_enqueue_style('fontawesome', 'https://use.fontawesome.com/releases/v5.8.2/css/all.css', array(), '5.8.2', 'all');
wp_enqueue_style('my', get_template_directory_uri() . '/css/style.css', array(), '1.0.0', 'all');
wp_enqueue_script('my', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_script_init');

これでstyle.cssとscript.jsがそれぞれ読み込まれるようになりました!

そして、それぞれheader.phpとfooter.phpに以下のように書いていきます。

header.php

<meta property="og:description" content="">
<meta name="twitter:card" content="summary_large_image">

<!--
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css?ver=5.8.2">
<link rel="stylesheet" href="./css/style.css">
ここを置き換える
-->

<?php wp_head(); ?>
<link rel="icon" href="./img/icon-home.png">

footer.php

<div class="floating">
  <a href="#"><i class="fas fa-chevron-up"></i></a>
</div>

<!--
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="js/script.js"></script>
ここを置き換える。jqueryはWPデフォで読み込まれるので消してOK。
-->

<?php wp_footer(); ?>
</body>
</html>

これで読み込み完了です。
以上、ありがとうございました。

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
0