Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPBカップ
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressでJavaScriptとスタイルを正しく追加する方法

編集メモ: WPBeginner のパートナーリンクから手数料を得ています。手数料は編集者の意見や評価に影響を与えません。編集プロセスについて詳しく知る。

WordPressでJavaScriptとCSSスタイルシートを適切に追加する方法を学びたいですか?

多くのDIYユーザーは、プラグインやテーマ内のスクリプトやスタイルシートを直接呼び出すというミスを犯しがちだ。

この投稿では、WordPressでJavaScriptとスタイルシートを適切に追加する方法を紹介します。WordPressのテーマやプラグイン開発を学び始めたばかりの方には特に役立つ内容です。

Properly adding JavaScripts and styles in WordPress

WordPressでスクリプトとスタイルシートを追加する際のよくある間違い

WordPressプラグインやテーマの新規開発者の多くは、スクリプトやインラインCSSをプラグインやテーマに直接追加するという間違いを犯します。

スクリプトやスタイルシートのロードにwp_head関数を誤って使用する人がいます。

<?php
add_action('wp_head', 'wpb_bad_script');
function wpb_bad_script() {
echo 'jQuery goes here';
}
?>

上記のコードは簡単そうに見えるかもしれないが、WordPressでスクリプトを追加する方法としては間違っており、将来的に衝突が多くなる。

たとえば、手動でjQueryをロードし、別のプラグインが適切な方法でjQueryをロードする場合、jQueryが2回ロードされることになる。すべてのページでjQueryが読み込まれると、WordPressのスピードとパフォーマンスに悪影響を及ぼす。

また、この2つが異なるバージョンである可能性もあり、これもコンフリクトの原因となる。

とはいえ、スクリプトとスタイルシートを追加する正しい方法を見てみよう。

なぜWordPressでスクリプトとスタイルをエンキューするのか?

WordPressには強力な開発者コミュニティがあります。世界中から何千人もの人々がWordPressのテーマやプラグインを開発しています。

WordPressは、すべてが適切に動作し、他の人のつま先を踏まないようにするために、エンキュー・システムを備えています。このシステムは、JavaScriptとCSSスタイルシートをロードするプログラム可能な方法を提供します。

wp_enqueue_script関数とwp_enqueue_style関数を使うことで、WordPressにいつファイルを読み込むか、どこで読み込むか、依存関係は何かを指示します。

このシステムにより、開発者は同じサードパーティのスクリプトを何度も読み込むのではなく、WordPressにバンドルされているビルトインJavaScriptライブラリを利用することができます。これにより、ページの読み込み時間が短縮され、他のテーマやプラグインとの競合を避けることができます。

WordPressでスクリプトを正しくエンキューするには?

WordPressでスクリプトを正しく読み込むのはとても簡単です。以下は、プラグインファイル、テーマのfunctions.phpファイル、またはコード・スニペット・プラグインに貼り付けて、WordPressでスクリプトを適切に読み込むためのコード例です。

?php
function wpb_adding_scripts() {
 
wp_register_script('my_amazing_script', plugins_url('amazing_script.js', __FILE__), array('jquery'),'1.1', true);
 
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

説明する:

まず、wp_register_script()関数でスクリプトを登録します。この関数は5つのパラメータを受け取ります:

  • $handle– ハンドルはスクリプトのユニークな名前です。私たちのスクリプトの名前は “my_amazing_script” です。
  • src– srcはスクリプトの場所です。plugins_url関数を使って、プラグインフォルダーの適切なURLを取得しています。WordPressがそれを見つけたら、そのフォルダーの中からファイル名amazing_script.jsを探します。
  • deps– depsは依存関係を表します。私たちのスクリプトはjQueryを使用しているので、依存エリアにjQueryを追加しました。WordPressは、サイト上ですでにjQueryが読み込まれていなければ、自動的にjQueryを読み込む。
  • ver– スクリプトのバージョン番号。このパラメータは必須ではありません。
  • in_footer– スクリプトをフッターにロードしたいので、この値をtrueに設定しています。スクリプトをヘッダーにロードしたい場合は、この値をfalseにします。

wp_register_scriptですべてのパラメータをプロバイダーした後、wp_enqueue_script()でスクリプトを呼び出すだけで、すべてが実行されます。

最後のステップは、wp_enqueue_scriptsアクションフックを使って実際にスクリプトを読み込むことです。これはサンプルコードなので、他のすべてのすぐ下に追加しました。

これをテーマやプラグインに追加する場合、スクリプトが実際に必要な場所にこのアクションフックを置くことができます。これにより、プラグインのメモリ使用量を減らすことができます。

なぜスクリプトを登録してからエンキューするのか、不思議に思う人もいるかもしれません。これは、プラグインのコアコードを変更することなく、他のサイトオーナーがスクリプトの登録を解除できるようにするためです。

WordPressでスタイルを正しくエンキューする

スクリプトと同じように、スタイルシートもキューに入れることができる。以下の例を見てほしい:

<?php
function wpb_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );  
?>

wp_enqueue_scriptを使う代わりに、wp_enqueue_styleを使ってスタイルシートを追加します。

スタイルとスクリプトの両方にwp_enqueue_scriptsアクションフックを使っていることに注目してください。名前とは裏腹に、この関数は両方で動作します。

上記の例では、plugins_url関数を使って、エンキューしたいスクリプトやスタイルの場所を指定しています。

ただし、テーマで enqueue scripts 関数を使用している場合は、代わりにget_template_directory_uri()を使用します。子テーマを使用している場合は、get_stylesheet_directory_uri() を使用します。

以下にコード例を示す:

<?php
  
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/js/amazing_script.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

この投稿が、WordPressでJavaScriptとスタイルを適切に追加する方法を学ぶのに役立てば幸いです。また、WordPressのトッププラグインのソースコードで実際のコード例を学んだり、WordPressの投稿日やページでJavaScriptを簡単に追加する方法のガイドをチェックしたりするのもよいでしょう。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

36件のコメント返信を残す

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jean-Michel says

    Hi there,
    I followed what is said here but now I get an empty white page on my web site. Could someone give me a hint ?
    Thanks

  3. Zaved Hossain says

    This is nice, though my usual practice is to add wp_enqueue_script/style in a single line without registering. Coders need to be careful about the parameters, perhaps a little explanation of that would be helpful. For example, the different versions of jquery (your jquery script may require different version than the wordpress’) and where to add it (header or footer which is determined by the true/false parameter). The jquery script needs to be added in the header, (hence a ‘false’ needs to be passed as the param value), otherwise it may not work.

  4. Hansjörg Leichsenring says

    There are often a lot of style.css.
    How can I ensure the correct load-order with enque and make sure, that the child css is loaded last?

    Cheers from Germany
    Hansjörg

  5. Carlos Araya says

    How do I pass empty parameter to register_script? I want to make sure that they script is loaded at the bottom of the page but can’t find information whether this is the default behavior or not

    • Kerry Beeher says

      Bonjour,

      Thank you for your excellente resource. Merci !!!

      I am little novice and just begin my journey to learn PHP and how WordPress use wp_enqueue_script and wp_register_script to add JavaScript and CSS.

      I use this free plugin called Easy Code Manager to help run through your exemples:
      however I am not sure if this is right plugin to use.

      I read before that it is not the best idea to modifier code in functions.php so I wonder if this is ok to do?

      Will it not get change on a theme update?
      Sorry for question, I still learn WordPress.

      Merci,
      Kerry

  6. Vaibhav Bansal says

    I want to add an Amazon Ad
    I tried to add it in text widget, but it shows blank.
    Below is the code-

    This is my site-
    Help me. How do I add js on my site?

  7. pradyumna says

    i have inserted a javascript using this plugin but now i have to remove it, i have tried uninstalling and deactivating the plugin but the javascript still executes

  8. Vijay.Rajpal says

    Hello Sir,
    I am using esteem theme and I wanted to add some javascripts functionality to my website like lightbox. I have created a child theme and the code are as follows. in the functions.php.

    and I am getting an error:-Parse error: syntax error, unexpected '{' in E:\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-content\themes\esteem-child\functions.php on line 18
    Please Help I am using sublime as my text editor.
    Please Help!!!!!

  9. Pramod says

    hello…..
    i m adding .js file in js directory of wordpress and gives its reference of it in funcation.php
    but its not working

    wp_enqueue_script( ‘any-navigation’, get_template_directory_uri() . ‘/js/menu.js’);

  10. Bobbie says

    Thanks so much! I’ve been trying to add a custom .js file but this is the first explanation that the register_script was needed.

  11. colkav says

    Hey, great tutorial. I’m having an issue adding a Google Analytics related javascript, as described here:
    I’ve put the script in my child theme’s ‘js’ folder (having first stripped the html from the code).

    When i load up the page I keep getting the error :

    ReferenceError: Can’t find variable: ga
    (anonymous function)myscript.js:6

    …and it just dawned on me that maybe I need to add ‘analytics.js’ as a dependency!

    Does that sounds right? And if so, how would I add analytics as a dependency for my script? I’ve tried experimenting here to no avail :(

  12. xavi says

    Hi.
    thanks for this amazing post tutorial! But when you say “where to upload the script” you just can define head or footer (in all entire webpages!)? Could you define an especific page to load it? I just need it in one. Thanks for advance and keep working! Cheers.

  13. Skye Barcus says

    I am a total novice at js but do know html. I want to put this on a wordpress page:

    Basically, it’s a widget to join a GoToMeeting. This works if you just throw it into the body of an html page, but in WordPress, it gets supressed.
    Can you give me a “For Dummies” version of how to make this work?

  14. Tyler Longren says

    On the style loading piece, on line 6, wp_register_script, should be wp_register_style I believe.

  15. Dejan says

    I really like you site it is full of useful tips, however looks like you are not doing it “Properly” for CSS enqueue even though your title say that way :=) The right way would be :

    wp_register_style( ‘my-css-style’, get_template_directory_uri() . ‘/css/style.css’, array(), ‘1.0’, ‘all’ );
    wp_enqueue_style( ‘my-css-style’ );

    Keep up the good work… Cheers!

  16. Adrian Zumbrunnen says

    Thanks for the effort you put into this. It just feels wrong to have wp_enque_script for loading stylesheets. WordPress could eventually spit out script instead of the stylehseet syntax for it.

    Do you really embed that way?

    • WPBeginner Support says

      This tutorial shows how to load JavaScript and stylesheet files for your themes or plugins in WordPress. If by Embed you meant how we display code in articles, then we use Syntax Highlighter plugin for that.

      管理者

  17. oiveros says

    hi i’m kind of new on the wordpress theming , and reading about these topic, i wanted to ask you about something related to these . If i want to update the jquery library link how do i do it or where do i find the link i been trying to do it but i can’t find it. Thank you in advanced for your help

    • WPBeginner Support says

      If by updating jquery library link, you mean to add jquery from Google’s library. WordPress comes packed with jquery and to load it in your theme use this line in your theme:

      <?php wp_enqueue_script('jquery'); ?>

      管理者

      • oiveros says

        okey so if i want to have the latest jquery, i just use that line?, because somebody told me to use a plugin just for that, but i wanted to learn how to do it without a plugin

        • oliveros says

          Thank you for your answer, i found the post related to that issue here in your site.

  18. Elliott Richmond says

    Useful Syed, thanks.
    I recently had an issue loading a css file using _underscore as a framework, although the stylesheet was called mycustomstyles.css the theme was calling mycustomstyles.css?ver=xx and the theme wasn’t loading the file because of the naming of the file by appending ?ver=xx to the end of the name.
    Is that something to do with $ver default?

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。