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を簡単に追加する方法(2つの方法)

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

WordPressのページや投稿にJavaScriptを追加したいですか?

サイト全体、または特定のページや投稿にJavaScriptコードを追加する必要がある場合があります。WordPressの初期設定では、投稿に直接コードを追加することはできません。

この投稿では、WordPressのページや投稿にJavaScriptを簡単に追加する方法を紹介します。

How to easily add JavaScript in WordPress pages or posts (3 methods)

JavaScriptとは?

JavaScriptは、サーバー上ではなくユーザーのブラウザー上で動作するプログラミング言語です。このクライアントサイド・プログラミングにより、開発者はサイトを遅くすることなく、多くのクールなことができるようになります。

動画プレーヤーを埋め込んだり、電卓を追加したり、その他のサードパーティサービスを利用したい場合、WordPressサイトにJavaScriptコードスニペットをコピー&ペーストするよう求められることがよくあります。

典型的なJavaScriptのコード・スニペットは次のようなものだ:

<script type="text/javascript"> 
// Some JavaScript code
</script>

<!-- Another Example: --!>  
<script type="text/javascript" src="/path/to/some-script.js"></script>

しかし、WordPressの投稿やページにJavaScriptのコードスニペットを追加した場合、保存しようとするとWordPressによって削除されてしまいます。

とはいえ、サイトを壊すことなくWordPressのページや投稿にJavaScriptを簡単に追加する方法を見てみましょう。以下のクイックリンクから、使いたい方法に直接ジャンプできます。

方法1.WPCodeを使ってWordPressサイトの任意の場所にJavaScriptを追加する(推奨)

プラグインやツールが正しく動作するためには、JavaScriptのコードスニペットをコピー&ペーストしてサイトに貼り付ける必要がある場合があります。

通常、これらのスクリプトはWordPressブログのヘッダーまたはフッターセクションに配置されるため、すべてのページ表示でコードが読み込まれます。

例えば、Google アナリティクスをインストールする場合、サイト内のすべてのページでコードを実行する必要があります。

手動でheader.phpや footer.phpファイルにコードを追加することもできますが、テーマの更新や変更時に上書きされてしまいます。

そのため、WPCodeを使用してWordPressサイト全体の任意の場所にJavaScriptを追加することをお勧めします。

WPCodeは、WordPressで利用可能な最も強力なコードスニペットプラグインです。サイトのどのエリアにも簡単にカスタムコードを追加することができ、しかもすべて無料です。

まず、無料のWPCodeプラグインをインストールし、有効化する必要があります。詳しくは、WordPressプラグインのインストール方法のステップバイステップガイドをご覧ください。

有効化したら、Code Snippets ” Headers & Footerにアクセスしてください。

ここでは、「ヘッダー」、「本文」、「フッター」というラベルの付いた3つの区切りフィールドが表示されます。

Adding header & footer code snippets with WPCode

これらのボックスにJavaScriptコードを追加し、「保存」ボタンをクリックしてください。WPCodeは、サイトの各ページに追加したコードを自動的に読み込みます。

また、投稿日やページ内など、サイト上の任意の場所にコードスニペットを追加することもできます。

これを行うには、コード・スニペット ” + スニペットの追加に行き、’自分で作成’をクリックするだけです。

Create your own code snippet with WPCode

カスタムスニペットの作成」ページが表示されるので、コードのタイトルを追加し、「コードプレビュー」ボックスに貼り付けます。

その後、「コードタイプ」のドロップダウンメニューから「JavaScriptスニペット」を選択します。

Enter a jQuery/JavaScript snippet into WPCode

そして、「インサーター」のセクションが見つかるまでスクロールする。

あとはすべて、ドロップダウンメニューからコードの「場所」を選択するだけです。ページ、投稿、カスタム投稿タイプ」を探して、コードを表示させたいページや投稿の場所を選んでください。

Insert snippet before post in WPCode

WPCodeが段落の前後にスニペットを挿入する場合、投稿のどの段落の前後に挿入するかを選択することができます。

例えば、「番号の挿入」フィールドに1を入れると、コード・スニペットは最初の段落の前後に表示されます。2段落目には2を、といった具合です。

その後、画面上部のトグルをクリックして「有効化」に切り替え、その横にある「スニペットを保存」ボタンをクリックすればよい。

Activate and save snippet in WPCode

あなたのコード・スニペットをサイト上で公開するために必要なことはすべてこれだけです!

方法2.手動でWordPressにJavaScriptコードをコードを使って追加する(上級者向け)

この方法では、WordPressファイルにコードを追加する必要があります。この方法を使ったことがない場合は、WordPressでコードをコピー&ペーストする方法をご覧ください。

まず、WordPressサイトのヘッダーにコードを追加する方法を紹介します。以下のコードをコピーして、functions.phpに追加してください。

function wpb_hook_javascript() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_head', 'wpb_hook_javascript');

コードを使って特定のWordPress投稿にJavaScriptを追加する

個別投稿にのみJavaScriptを追加したい場合は、コードに条件ロジックを追加する必要があります。

次のコードを見てほしい:

function wpb_hook_javascript() {
  if (is_single ('5')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

上記のコードは、投稿IDが’5’に一致した場合にのみJavaScriptを実行します。5’を自分の投稿IDに置き換えてください。

投稿IDを見つけるには、JavaScriptを実行したい投稿を開いてください。そのページのURLの中に投稿IDがあります。

Find WordPress post ID

コードを使用して特定のWordPressページにJavaScriptを追加する

WordPressの個別ページにのみJavaScriptを追加したい場合は、上記のようにコードに条件ロジックを追加する必要がある。

次の例を見てみよう:

function wpb_hook_javascript() {
  if (is_page ('10')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

上記のコードは、ページIDが’10’の場合にのみJavaScriptを実行します。本当に〜してもよいですか?

ページIDは、上記と同じ方法で見つけることができます。JavaScriptを実行させたいページを開き、URLのページIDに注目してください。

フッターのコードを使って特定のWordPress投稿やページにJavaScriptを追加する

JavaScriptをヘッダーではなくサイトのフッターで実行したい場合は、以下のコード・スニペットをサイトに追加してください。

function wpb_hook_javascript_footer() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');

このコード・スニペットは、wp_headの代わりにwp_footerにフックします。上記の例のように、特定の投稿やページにJavaScriptを追加する条件分岐タグを追加することもできます。

注:これらの方法は初心者やサイトオーナー向けです。WordPress テーマやプラグイン開発を学んでいる場合は、JavaScript とスタイルシートをプロジェクトに適切にエンキューする必要があります。

この投稿が、WordPressのページや投稿にJavaScriptを簡単に追加する方法を学ぶのにお役に立てば幸いです。また、最高のブログプラットフォームの選び方に関するガイドと、あなたのサイトに最適なAIチャットボットソフトウェアのエキスパートピックもご覧ください。

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

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

  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. Jiří Vaněk says

    WPCode saved my entire website like this, which I already had completed, but eventually we found out that the menu works very poorly on mobile devices. I found a solution in the form of JavaScript, but I didn’t know where or how to insert it into the website. This saved me all the work and solved the problem with closing the menu on mobile devices.

  3. wing says

    i wonder why not use the most simple method, just directly use the wordpress “Custom HTML” block to insert Javascript code to a post or page. I have try it and test it. No problem. very very very simple method.

    • WPBeginner Support says

      It would depend on the specific code, the methods we show in this guide are to add the code to the head section as most JavaScript wants to be run in the head section.

      管理者

  4. Rejane says

    I have an active child theme and I used the “Insert Headers and Footer” plugin to add a JavaScript code for an email marketing service. It worked out! But unfortunately, I had to cancelled my account with this service and now I would like to remove the JavaScript code. How do I do this when I am using a child theme? Is there any easy way or another plugin for this?

    • WPBeginner Support says

      You would remove the code from the Insert Headers and Footers plugin and it would remove the code from your site :)

      管理者

    • WPBeginner Support says

      It should be at the top of the edit page. if you are using the classic editor then it would be under Screen Options.

      管理者

  5. Eleni says

    I’m not getting the Custom Fields option in the Screen Options tab. I’m using a self-hosted website and have installed and activated the Code Embed plugin

    • WPBeginner Support says

      If you’re using the Block editor then the setting has moved under the preferences area.

      管理者

  6. Ashley says

    This site is AMAZING!!! This is the third post in a row where I’ve hit the jackpot getting what I needed and did it in the easiest way possible. Thank you!!

  7. Dude says

    Hey, great stuff WPbeginners! The second method worked like a charm. I did have a question though. If I wanted to add another js code for another purpose, how should the code start. Because anything I add after the code is greyed out. I’m at a loss here. I want it to do the same but for another page. Any ideas will be appreciated.

    • WPBeginner Support says

      It would heavily depend on the code you are using but you would want to ensure the code is before the /script tag

      管理者

  8. Martin says

    Question on Method 3:

    After inputting the value and clicking on the “add custom field”, how do I get the code to display on my website frontend?

    Should I insert “{{CODEmyjscode}}” using a shortcode widget or text editor on the page?

  9. Bret Bernhoft says

    When I first began working with WordPress, JavaScript seemed like an impossibility for me. But fast forward to today and I’m writing the language every day; often in association with WordPress.

    I wish it had been clearer to me how easy it would have been to write JavaScript, when I first began this journey. Thank you for the tools and tips. I’ll have to give this a try.

  10. Kat says

    I tried adding custom JS in my post, but nothing happens. I followed your exact directions for Method 3, but when I go to preview the page it’s just blank space where the JS is supposed to be. Any idea why?

    • WPBeginner Support says

      You would want to take a look at the plugin’s FAQ for the most common reasons for that issue and how to resolve it.

      管理者

  11. Samuel says

    How does this work with the new WordPress block system?

    I’m trying to embed this in a page, but it just shows as {{code1}} on the preview

    • WPBeginner Support says

      It would depend on the method you are using on your site for the plugin, they have an update in their FAQ section for how to use it at the moment.

      管理者

  12. James says

    Hi. I have employed a programmer to create a tool, which he did in Javascript. I have been using Weebly but Weebly has become unresponsive to requests for help, to which hundreds of blogs testify. So, I’m looking at alternatives to Weebly. Could WordPress handle a 2 MB javascript tool?

    Thanks,

    • WPBeginner Support says

      Your hosting would determine if a tool like that could be used not the platform for your website and depending on how the tool was set up would determine if you can transfer the tool.

      管理者

  13. Matt says

    What if I need to add the script just on a single page but in the head not the body? I am trying to add a google conversion pixel just to my form submit thank you page.

    • WPBeginner Support says

      You would want to take a look at the section of the article called: Adding JavaScript to a Specific WordPress Post or Page Using Code :)

      管理者

  14. Manjeet Chhillar says

    Thank you for this very helpful post.

    My query is: How can I implement “Method 2” on multiple posts. Do i need to add Post ID of every single post separated by comma?

    • WPBeginner Support says

      yes, you would need to place the commas outside the single quotes and start a new set of quotes for this method

      管理者

  15. Deborah says

    Thank you for sharing the three methods WordPress users can use to add JavaScript to posts or pages. From what I read on the Insert Headers and Footers plugin page in the repository, the plugin doesn’t use the enqueue method to add the scripts. Which is the recommended method to add scripts in WordPress.

    Did I misunderstand? Or is Insert Headers and Footers using enqueue to add scripts? If it’s not using enqueue, do you know when the plugin will be updated to use enqueue?

    • WPBeginner Support says

      The plugin is not enqueueing scripts added to it at the moment as not everything added with our plugin may not want to be enqueued. If you would like to enqueue the added code you would want to use another method.

      管理者

  16. Dave G says

    Nice, thanks for that. It so happen that the exact post ID I needed to run javascript on was number 16. “`if (is_single (’16’)) { “`

    Are you from the future?

    :)

  17. Thomas says

    I need to add a script to all posts in my blog. I have the plugin to each individual post. Thing is, there are thousands of posts and we need to add the script to all of them. Any suggestions? Thank you in advance.

    • WPBeginner Support says

      The Insert Headers and footers option will put a code on every post and page for you if they are using the same code.

      管理者

      • Thomas says

        Thank you for your quick reply.

        We only want the script to run on Posts. We do not want it to run on all pages.

        • WPBeginner Support says

          If you had a widget that is only added to posts you could try adding the code in a widget.

  18. Ann says

    I’ve tried using the Headers and Footers scripts and the jQuery just doesn’t seem to be working properly.

    • WPBeginner Support says

      It would depend on the specific code you are adding to the site for the possible reasons it could not be working. You may want to ensure with who you took the code from that the code itself is working.

      管理者

    • WPBeginner Support says

      Our plugin is currently working from testing but we will certainly take another look at it.

      管理者

  19. Remco says

    Thank you for this great post!
    Is it possible to implement Structured Data on Woocommerce pages with this method (JSON-LD)?

    • WPBeginner Support says

      You likely could but if you have an SEO plugin you are currently using you would want to check with that plugin to see if the plugin does that already.

      管理者

  20. graham says

    A well-presented roundup of the better-known options for what is becoming a common need. However, many WordPress users are not (and do not want to be) programmers. For them, JavaScript in any form is too frightening; that’s why they use WordPress with its promise of “no programming required”.

    There’s another possibility; to use custom scripts instead of JavaScript, and embed them directly in the page. You can put them in any component, though I prefer .

    All you need then is something that can compile and run the script. It’s hard to find plugins that can do this; my own searches haven’t yet turned up any. However, as a JavaScript programmer myself, I was able to write one and put it in the library as EasyCoder. The scripts resemble English, have about the same complexity as SQL and can do most of the things commonly required to manage content and interactivity in a web page. EasyCoder is also fully pluggable so other programmers can add modules themselves.

返信を残す

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